Alamofire progress callback stops working after returning from background

*爱你&永不变心* 提交于 2019-12-08 10:45:03

问题


I have a method that uploads (video) data to the server, and it looks like this:

 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)
            }
        }
    }

So the problem is, I can't update UI properly when returned from background (while in the middle of upload).

Why this progress callback stops working (after returning from background) ?


回答1:


Alamofire isn't really compatible with background sessions. Since it's a closure-based API that can't be persisted when the app goes into the background, your progress closures aren't being reconnected when the app is foregrounded. We recommend you use URLSession directly or use the background task API instead of background sessions.




回答2:


So what I have done, is used background task (also did it without Alamofire completely) and it worked. Like this:

 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")
                    }
            })

Now progress callbacks work normally and you can still use Alamofire to pack the multipartformdata as I was using it, or for whatever reason you are using it.



来源:https://stackoverflow.com/questions/54983913/alamofire-progress-callback-stops-working-after-returning-from-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!