uploadTask使用Swift中的AFNetworking进度

时间:2015-01-20 17:54:33

标签: swift afnetworking nsprogress

我试图将NSProgress与AFNetworking一起使用,这是我使用的代码

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

文件已正确上传,但事实并非如此 - 我只打印了一次进度值(&#34;进度:0.0&#34;)然后我就是&#39; m以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;
}

我做错了什么?我应该设置&#34; var进度:NSProgress?&#34;不同还是还有其他我不知道的东西?

1 个答案:

答案 0 :(得分:1)

哦,我已经解决了 - 我需要从进度中移除观察者:

let uploadTask: NSURLSessionUploadTask = sessionManager.uploadTaskWithStreamedRequest(request, progress: &progress, completionHandler: { (response, responseObject, error) in
//...
progress?.removeObserver(self, forKeyPath: "fractionCompleted", context: nil) // added this line
//...
})