UIProgressView进度更新在AlamoFire(异步)调用中非常慢 [英] UIProgressView progress update very slow within AlamoFire (async) call
问题描述
在AlamoFire获取请求中,我正在尝试更新进度栏。像这样:
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>...
}
由于某些原因,这需要花费几秒钟的时间,如果我使用 dispatch_sync
,该应用程序似乎就此卡住了,但UI却没有冻结(活动指标微调器继续运行)。
我还想指出的是,一旦应用程序点击了此代码,它将继续执行后的代码,就好像它已被执行一样。然后大约在6秒钟后执行它,就好像没有在主线程上调用它一样。
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.
我也只是尝试这样做而不是使用Notification。
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)
})
这似乎比通知要慢。
我很困惑为什么会这样,因为我告诉它在主线程中进行更新。我也感到困惑,为什么通知实际上要快一些。
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.
推荐答案
在Alamofire中,有一种更好的方法。当数据任务上发生数据传输时,您可以使用 progress
闭包自动获取回调。这是来自README监视下载请求进度的示例。
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)
}
这篇关于UIProgressView进度更新在AlamoFire(异步)调用中非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!