Photo by Les Triconautes on Unsplash

Tip: never process data on the main thread

Be aware of the thread you are on and handle network response data on a background thread

boaz frenkel
Published in
2 min readFeb 23, 2020

--

Lately, I got the chance to examine several homework assignments as part of recruiting an iOS developer process. I noticed a common mistake from different experience level developers. They process data (JSON) on the main thread after a server call.

As iOS developers know, long-running tasks such as networking should (usually) be executed in the background, and provide some completion handler to signal completion.

It is widespread when using a third party networking framework to get this completion block on the main thread. For example, in the popular AlamoFire framework the completion handler is run on the main thread by default. But it also provides ways to customize this, of course. (see the example in the next paragraph).

What this means is you:
1) Get the response of a network call on the main thread.
2) Then on the main thread, parse the response.
3) Then on the main thread, manipulate the data in different ways if needed.
4) Then use the data to update the UI or something else.
But what if you need to parse a very lengthy response?
What if you need to do more processing on the response, e.g., sorting, dates formatting, etc.?

I see no reason for doing this kind of work on the main thread, and I strongly encourage you to use a background thread for this work.
Or even better, make sure you get the response on a background thread, do the work you need, and only then return to the main thread.

Here is an example with AlamoFire, when you don’t want the default behavior, you can pass a queue to theresponse which is then used to dispatch your completion handler and manually call back to the main queue if necessary.

Since we know that updating UI on a thread other than the main thread is a common mistake that can result in missed UI updates, data corruptions, and crashes — Don’t forget to return to the main thread!

--

--