3

Inside an AlamoFire get request I'm trying to update my progress bar. Like so:

alamofireManager.request(.GET, urlPath, parameters: params).responseJSON{(request,response,JSON,error) in
    ...<code here>...
    dispatch_async(dispatch_get_main_queue(), {
        NSNotificationCenter.defaultCenter().postNotificationName(LoginVCHideSpinnerAndShowProgressBarName as String, object: self)
    })
    ...<more code here>...
}

For some reasons this takes a few seconds to execute and if I use dispatch_sync instead the app just seems to get stuck at that point but the UI doesn't freeze up (the activity indicator spinner keeps going). I also want to point out that once the app hits this code it continues on to the code after it as if its been executed. It then is executed about 6 seconds later as if it wasn't being called on the main thread.

I have also just simply tried doing this instead of using a Notification.

dispatch_async(dispatch_get_main_queue(), {
    loginVC.progressBar.hidden = false
    loginVC.indicator.hidden = true
    loginVC.progressBar.setProgress(0.1, animated: true)
})

This seems to be slower than the Notification.

I am very puzzled to why this is happening since I am telling it to update in the main thread. I am also confused why the notification is actually a little bit faster.

Boid
  • 1,161
  • 1
  • 11
  • 21

1 Answers1

7

There's a MUCH better way to do this in Alamofire. You can use the progress closure to automatically get a callback when a data transfer occurs on your data task. Here's an example from the README monitoring progress for a download request. The same applies for a data request.

let progressView = UIProgressView(progressViewStyle: .Bar)

let params = ["foo": "bar"]
let URLString = "http://httpbin.org/get"

let request = Alamofire.request(.GET, URLString, parameters: params)
request.progress { _, _, _ in
    progressView.setProgress(request.progress.fractionCompleted, animated: true)
}
request.responseJSON { request, response, json, error in
    println(request)
    println(response)
    println(json)
    println(error)
}
cnoon
  • 16,575
  • 7
  • 58
  • 66