4

I'm trying to use NSProgress with AFNetworking, this is the code I'm using

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

The file is uploaded correctly, but that's not the case - I'm only getting the progress value printed once ("progress: 0.0") and then I'm ending with EXC_BAD_ACCESS inside AFURLSessionManager.m:

#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;
}

What am I doing wrong? Should I set "var progress: NSProgress?" differently or is there something else I'm missing?

pJes2
  • 623
  • 1
  • 8
  • 13

1 Answers1

1

Oh, I've fixed it - I needed to remove the observer from progress:

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