Reputation: 823
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
Upvotes: 0
Views: 698
Reputation: 15464
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).
Upvotes: 1
Reputation: 5241
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.
Upvotes: 1