Swift 3- Update UI from main thread

假如想象 提交于 2019-12-04 14:38:55
Rob

In your code sample here, you are dispatching the reloadData to the main queue. But that is unnecessary because the closure of responseJSON is already running on the main queue, so there's no need to dispatch anything. So, you should remove that dispatch of reloadData to the main queue.

Now, if you were using URLSession, which defaults to running closures on a background queue or if you explicitly provided a background queue as the queue parameter of responseJSON, then, yes, you'd dispatch reloadData to the main queue. But that's not the only thing you'd need to make sure to dispatch to the main queue, as your model updates and the HUD updates should run on the main queue, too. But that's moot, because this responseJSON is already running its completion handler on the main queue.

Then, in comments, you later ask if all of this is running on the main queue, whether you should dispatch this all to a background queue like you did in a previous question (presumably with the intent of wanting to avoid blocking the main queue).

It turns out that this is not necessary (nor desirable) because while the processing of the response in the responseJSON completion handler runs on the main queue, the network request, itself, is performed asynchronously. You would only dispatch the completion handler code to a background queue (or specify a background queue as a parameter to responseJSON) if you were doing something computationally intensive in the closure. But you don't have to worry about the network request blocking the main queue.

Bottom line, Alamofire makes this simple for you, it runs the request asynchronously but runs its completion handlers on the main queue. It eliminates much of the manual GCD code that you mess around with when using URLSession.

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