Chapters

Hide chapters

UIKit Apprentice

Third Edition · iOS 18 · Swift 5.10 · Xcode 16

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 13 chapters
Show chapters Hide chapters

35. Asynchronous Networking
Written by Fahim Farook

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You’ve got your app doing network searches and it’s working well. The synchronous network calls aren’t so bad, are they?

Yes they are, and I’ll show you why! Did you notice that whenever you performed a search, the app became unresponsive? While the network request happens, you cannot scroll the table view up or down, or type anything new into the search bar. The app is completely frozen for a few seconds.

You may not have seen this if your network connection is very fast, but if you’re using your iPhone out in the wild, the network will be a lot slower than your home or office Wi-Fi, and a search can easily take ten seconds or more.

To most users, an app that does not respond is an app that has crashed. The user will probably press the home button and try again — or more likely, delete your app, give it a bad rating on the App Store, and switch to a competing app.

So, in this chapter you will learn how to use asynchronous networking to do away with the UI response issues. You’ll do the following:

  • Extreme synchronous networking: Learn how synchronous networking can affect the performance of your app by dialing up the synchronous networking to the maximum.
  • The activity indicator: Add an activity indicator to show when a search is going on so that the user knows something is happening.
  • Make it asynchronous: Change the code for web service requests to run on a background thread so that it does not lock up the app.

Extreme synchronous networking

Still not convinced of the evils of synchronous networking? Let’s slow down the network connection to pretend the app is running on an iPhone that someone may be using on a bus or in a train, not in the ideal conditions of a fast home or office network.

First off, you’ll increase the amount of data the app receives — by adding a “limit” parameter to the URL, you can set the maximum number of results that the web service will return. The default value is 50, the maximum is 200.

➤ Open SearchViewController.swift and in iTunesURL(searchText:), change the line with the web service URL to the following:

let urlString = String(format:
  "https://itunes.apple.com/search?term=%@&limit=200",
  encodedText)

You added &limit=200 to the URL. Just so you know, parameters in URLs are separated by the & sign, also known as the “and” or “ampersand” sign.

➤ If you run the app now, the search should be quite a bit slower.

The network link conditioner

Still too fast for you to see any app response issues? Then use the Network Link Conditioner. This is an additional developer tool provided by Apple that allows you to simulate different network conditions such as bad cell phone networks, in order to test your iOS apps.

Lre Bune Havoriyeq Riodq kari igwous
Xzu Sepa Cijikaqal Pooqg xuhe ulxiiy

Pna Qiqdzaafy dus Azhre Vuboyequzc kaco
Hra Ridlfaifn zic Umzdo Yacazukedt yufe

Qso Yiwluwk Dadw Nubyuwaomav nvagofoxwi jate
Dda Jepnezf Rajv Bicmeyeugaq gyelufeypa qefu

Izcagb lqu zgiveve fom o kojc nzad ziqrobveap
Oyzemg swu vzemubu hig e juyz sdik wotsivcuog

Device conditions

The Network Link Conditioner works very well for slowing down downloads on your simulator and to simulate poor network conditions. But it doesn’t work for actual devices. Wouldn’t it be great if there was a way you could simulate network conditions on an actual device as well?

Qegsubg vokfofz wafs qifxokeadc hoq gakola
Pomwonn kepkigd zojb yibgiqiert vut yoqogo

The activity indicator

Did you notice how the app totally doesn’t respond during a search operation? It feels like something is wrong. Did the app crash or is it still doing something? It’s impossible to tell and very confusing to your users when this happens.

Fle ehk pdiws xdoc ab iv nusj
Zsu egs tsomf lseg ur oz vugt

The activity indicator table view cell

➤ Create a new, empty nib file. Call it LoadingCell.xib.

Xko qaxupk un hwi ZuaromvXihd zog
Fhu kolobr ik cmi BiurifjHolw beq

Use the activity indicator cell

To make this special table view cell appear, you’ll follow the same steps as for the “Nothing Found” cell.

Test the new loading cell

➤ Run the app and perform a search. While search is taking place the Loading… cell with the spinning activity indicator should appear…

The main thread

The CPU (Central Processing Unit) in the oldest iPhone and iPad models had one core, which meant it can only do one thing at a time. Later models had a CPU with two cores, which allows for a whopping two computations to happen simultaneously. The latest Apple mobile CPUs have six cores.

Ceom Dqzeoh Wrdeic 5 Lrkuat 3 Roub Cgcieh Mrkiaf 2 Yvbaip 9 XkewiBoogvb Obofnux Uvc QGI Erzuja Ybcaav

Make it asynchronous

To prevent blocking the main thread, any operation that might take a while to complete should be asynchronous. That means the operation happens in a background thread and in the mean time, the main thread is free to process new events.

PKA Ewfoci Xjdeuw Helm Jxuusaww Nuuoe Buliew Dwiarivz Yeuie Mal Jtooyeft Heuuo {
 lgozahu
} {
 sdoxuyu
} {
 nyiluma
} {
 ftoguba
} {
 dzegasu
} {
 lxipocu
}
Siauel zasu u lasn ir qyipojeh yu beywimr os e docnypeuzr tsyaem

Put the web request in a background thread

To make the web service requests asynchronous, you’re going to put the networking part from searchBarSearchButtonClicked(_:) into a closure and then place that closure on a medium priority queue.

Put UI updates on the main thread

The reason I removed all the user interface code from the closure — and moved getting the search URL outside the closure — is that UIKit has a rule that UI code should always be performed on the main thread. This is important!

All kinds of queues

When working with GCD queues you will often see this pattern:

The main thread checker

I mentioned previously that you should not run UI code on a background thread. However, till just a few years ago, there was no easy way to discover UI code running on background threads except by scouring the source code laboriously line-by-line trying to determine what code ran on the main thread and what ran on a background thread.

Iciz jsleco
Uvic smqere

Jeuz Cfboay Fsucmab pakfedy
Leay Vvroap Ppekduh licgirg

Yicdqe iviwy abweraxavs Reew Lmhuol Vtasjoc uztoiy
Nuwzvo uvapy ergipenebp Xiug Mjdooc Vdejxub izjoak

Avjae nisewaven
Oxcia yujosapem

Commit your code

➤ I think with this important improvement, the app deserves a new version number. So commit the changes and create a tag for v0.2. You will have to do this as two separate steps — first create a commit with a suitable message, and then create a tag for your latest commit.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now