简体   繁体   English

API响应关闭中的iOS Swift 3 DispatchQueue.main.async()

[英]iOS Swift 3 DispatchQueue.main.async() in API response closure

So I'm parsing a json response from an API service and I update the UI in the response parse closure which is supposed to happen asynchronously. 因此,我正在从API服务解析json响应,并在响应解析闭包中更新了UI,这应该是异步发生的。

I noticed that - even though the API's response is very fast as I can tell from the console log - the UI doesn't update instantly. 我注意到-尽管从控制台日志可以看出,即使API的响应非常快,但UI不会立即更新。 It takes a few seconds to update. 更新需要几秒钟。

So I searched a bit and I found out that putting my UI update code inside DispatchQueue.main.async() fixes it. 因此,我进行了一些搜索,发现将UI更新代码放入DispatchQueue.main.async()解决此问题。

Why is that the case? 为什么会这样? Aren't closures supposed to be async and take care of all that? 闭包不是应该异步处理所有这些吗? Am I misunderstanding something? 我误会了吗? Thanks 谢谢

Yes my friend, you are missing something here. 是的,我的朋友,您在这里缺少什么。 Closures are not inherently supposed to be async. 闭包并不是天生就应该是异步的。 Even the normal functions that you defined are closures. 甚至您定义的普通函数都是闭包。 Closures are not the magic wand that would take care of all for you. 封闭不是魔咒,它会为您照顾所有人。 Its just a block of statements which can be passed around. 它只是可以传递的语句块。

As you say that the response comes fast but UI does not update automatically, it might be taking time in parsing. 正如您所说的那样,响应很快,但是UI不会自动更新,因此解析可能会花费一些时间。 Make sure that you are not doing the parsing part on main queue, only UI updations should be on main queue. 确保您没有在主队列上进行解析,只有UI更新应在主队列上。

Are you using URLSessions 's dataTask(with:completionHandler:) api? 您是否在使用URLSessionsdataTask(with:completionHandler:) API? If this is the case completionHandler is called from background queue. 如果是这种情况,则从后台队列中调用completionHandler That's why it takes some time to update UI(Be careful here. You can get random crashes too). 这就是为什么需要一些时间来更新UI(请注意这里。您也可能会随机崩溃)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM