简体   繁体   中英

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.

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. 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.

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. Make sure that you are not doing the parsing part on main queue, only UI updations should be on main queue.

Are you using URLSessions 's dataTask(with:completionHandler:) api? If this is the case completionHandler is called from background queue. That's why it takes some time to update UI(Be careful here. You can get random crashes too).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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