在 Alamofire 5 中,可以使用 backgroundSessionConfiguration 来创建后台上传任务。在后台操作期间,上传可能会失败,因此需要设置重试机制。以下是创建适合后台上传任务的 Session Manager 的代码示例:
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.upload")
let manager = Alamofire.Session(configuration: configuration)
manager.upload(multipartFormData: { ... },
to: "https://httpbin.org/post",
headers: HTTPHeaders(headers),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
debugPrint(encodingError)
}
})
注意:创建 backgroundSessionConfiguration 后,需要使用相同的 identifier 值来创建 manager。 如果在后台操作期间上传任务失败,Alamofire 5 不提供尝试重试机会的等价物,你需要手动重试。