从后台返回后,Alamofire进度回调停止工作

时间:2019-03-04 13:05:09

标签: ios swift background alamofire multipartform-data

我有一种将(视频)数据上传到服务器的方法,它看起来像这样:

 static func upload(video data:Data, named name:String, parameters:[String:Any],  toUrl url:URL, progress:@escaping (Double)->Void, completion:@escaping(Bool)->Void){
manager = Alamofire.SessionManager(configuration: URLSessionConfiguration.background("com.app.backgroundtransfer")
        manager.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(data, withName: "filedata", fileName: name, mimeType: "video/quicktime")

            for key in parameters.keys{

                if let val = parameters[key] as? String{

                    multipartFormData.append(val.data(using: .utf8, allowLossyConversion: false)!, withName: key)
                }
            }

        }, to: url) {
            (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.uploadProgress(closure: { (uploadProgress) in

                    progress(uploadProgress.fractionCompleted)
                    //this one stops getting called

                })
                upload.responseJSON { response in
                   // but this one gets called at the end.
                }
            case .failure(let encodingError):
              print(encodingError)
            }
        }
    }

问题是,从后台返回时(在上传中间),我无法正确更新UI。

为什么此进度回调停止工作(从后台返回后)?

2 个答案:

答案 0 :(得分:2)

Alamofire与后台会话并不完全兼容。由于这是一个基于闭包的API,当应用程序进入后台时无法持久保存,因此当应用程序前台运行时,不会关闭您的进度闭包。我们建议您直接使用URLSession或使用后台任务API代替后台会话。

答案 1 :(得分:1)

因此,我所做的是使用后台任务(在没有Alamofire的情况下也完全完成了此任务)并且有效。像这样:

 var backgroundTask: UIBackgroundTaskIdentifier = .invalid

    func registerBackgroundTask() {
        backgroundTask = UIApplication.shared.beginBackgroundTask {
            self.endBackgroundTask()
        }
        assert(backgroundTask != .invalid)
    }

    func endBackgroundTask() {
        print("Background task ended.")
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = .invalid
    }

 APIClient.manager = Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: "com.app.backgroundtransfer"))
            self.registerBackgroundTask()

            APIClient.upload(video: video, named: videoDetailsModel.videoURL!.lastPathComponent, parameters: self.uploadParameters, toUrl: url, progress: {[weak self] (percentage) in
                guard let `self` = self else {return}

                print("Progress \(percentage)")
                self.progressBar.progress = CGFloat(percentage)
                }, completion: { [weak self] (success) in
                    guard let `self` = self else {return}
                    if(success){
                        print("Video successfully uploaded")
                        self.endBackgroundTask()
                        self.progressBar.progress = 1.0
                    }else{
                        print("Video upload was not successfull")
                    }
            })

现在进度回调可以正常工作,您仍然可以使用Alamofire打包多部分数据,就像我正在使用它一样,或者出于任何原因使用它。