我正在尝试将NSProgress与AFNetworking一起使用,这是我正在使用的代码 //func upload...//...let request: NSMutableURLRequest = AFHTTPRequestSerializer().multipartFormRequestWithMethod("POST", URLString: url, parameters: s3pa
//func upload... //... let request: NSMutableURLRequest = AFHTTPRequestSerializer().multipartFormRequestWithMethod("POST", URLString: url, parameters: s3parameters, constructingBodyWithBlock: { formData in let data: AFMultipartFormData = formData data.appendPartWithFileURL(fileURL, name: "file", error: nil) }, error: nil) request.setValue("application/json", forHTTPHeaderField: "Accept") let sessionManager: AFURLSessionManager = AFURLSessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration()) var progress: NSProgress? let uploadTask: NSURLSessionUploadTask = sessionManager.uploadTaskWithStreamedRequest(request, progress: &progress, completionHandler: { (response, responseObject, error) in //... }) uploadTask.resume() progress?.addObserver(self, forKeyPath: "fractionCompleted", options: NSKeyValueObservingOptions.Initial, context: nil) //... override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { let progress: NSProgress = object as NSProgress println("progress: \(progress.fractionCompleted)") }
文件是正确上传的,但事实并非如此 – 我只打印了一次进度值(“progress:0.0”),然后我以AFURLSessionManager.m中的EXC_BAD_ACCESS结束:
#pragma mark - NSURLSessionTaskDelegate - (void)URLSession:(__unused NSURLSession *)session task:(__unused NSURLSessionTask *)task didSendBodyData:(__unused int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { self.progress.totalUnitCount = totalBytesExpectedToSend; <<< EXC_BAD_ACCESS self.progress.completedUnitCount = totalBytesSent; }
我究竟做错了什么?我应该设置“var progress:NSProgress?”不同还是还有别的东西我不见了?
哦,我已经修好了 – 我需要从进度中移除观察者:let uploadTask: NSURLSessionUploadTask = sessionManager.uploadTaskWithStreamedRequest(request, progress: &progress, completionHandler: { (response, responseObject, error) in //... progress?.removeObserver(self, forKeyPath: "fractionCompleted", context: nil) // added this line //... })