我正在尝试将 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)")
}
该文件已正确上传,但事实并非如此 - 我只打印一次进度值(“进度: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”吗?不同还是我还缺少其他东西?