gpt4 book ai didi

ios - 当应用程序在后台运行时 Alamofire 完成

转载 作者:行者123 更新时间:2023-11-30 12:50:13 26 4
gpt4 key购买 nike

我正在尝试在同一请求中创建图像和视频的后台上传。我为后台任务创建了一个自定义 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)
}
}
}

问题在于,仅当应用程序位于前台时才会调用请求 (*) 的完成。似乎当应用程序进入后台时,alamofire 仍然继续上传(因为 URLSessionConfiguration.background),但仅当应用程序再次进入前台时才调用完成。如果应用程序在后台时上传完成,我想显示 UNNotification。可能吗?

最佳答案

当应用程序在后台运行时,您的类(class)还活着吗?仅当所写入的类在内存中时,完成 block 才会执行(可能完成 block 包含弱 self )。

关于ios - 当应用程序在后台运行时 Alamofire 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com