【问题标题】:Alamofire completion when app in background应用程序在后台时完成 Alamofire
【发布时间】:2016-12-12 18:17:39
【问题描述】:

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

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    当应用程序在后台时,你的班级还活着吗?只有当写入的类在内存中时,完成块才会执行(可能是完成块包含弱自身)。

    【讨论】:

    • 具有完成闭包的viewController在捕获列表中具有弱自身,但是当应用程序进入后台时,此视图控制器不会被破坏。 Morover,当应用程序在前台返回时,会调用完成并显示通知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2018-12-07
    • 2018-11-19
    • 2015-12-17
    • 2011-12-27
    • 2016-01-04
    相关资源
    最近更新 更多