我正在尝试在同一请求中创建图片和视频的后台上传。我为后台任务创建了一个自定义SessionManager:
let configuration = URLSessionConfiguration.background(withIdentifier: "by.wink.citynews.upload.background")
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
let sessionManager = Alamofire.SessionManager(configuration: configuration)
然后我使用以下代码发出请求:
func uploadNews(newsCreating: NewsCreating, progressHandler: @escaping (Double)->Void, completion: @escaping NewsCreatingCallback) {
let parameters: [String: String] = ["text" : newsCreating.text, "category" : newsCreating.category.id]
backgroundManager.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
newsCreating.images.forEach({ image in multipartFormData.append(image.jpegCompressedData, withName: "images[]", fileName: "\(image.name).jpg", mimeType: "image/jpeg") })
if let video = newsCreating.video {
multipartFormData.append(video.url, withName: "video", fileName: "\(video.name).mp4", mimeType: "video/mp4")
}
}, to: URL(string: "http://api.someapi.com/endpoint")!, method: .post) { encodingResult in
switch encodingResult {
case .success(let uploadRequest , _, _):
// custom response for auto-parsing of json
uploadRequest.responseServiceObject { (response: DataResponse<ServiceResult<NewsReporting, NewsCreatingServiceError>>) in
// (*) alamofire completion, here is the problem.
switch(response.result) {
case .success(let serviceResult):
if serviceResult.success {
completion(.success(serviceResult.response))
} else {
completion(.clientError(serviceResult.errors))
}
case .failure(let error):
completion(.error(error as! CityNewsError))
}
uploadRequest.uploadProgress() { requestProgressHandler in
progressHandler(requestProgressHandler.fractionCompleted)
}
}
case .failure(let error):
print(error)
}
}
}
问题是只有当app在前台时才会调用请求(*)的完成。似乎当app进入后台时,alamofire仍然继续上传(因为URLSessionConfiguration.background),但只有当app再次进入前台时才会调用完成。我想在应用程序处于后台时上传完成时显示UNNotification。有可能吗?
答案 0 :(得分:0)
当应用在后台时你的课程还活着吗?只有当它写入的类在内存中时,才会执行完成块(可能是完成块包含弱自我)。