UIProgressView progress update very slow within AlamoFire (async) call

不问归期 提交于 2019-12-06 09:25:50

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/30385096/uiprogressview-progress-update-very-slow-within-alamofire-async-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!