Appendix C. How Asynchronous Works
Beginners sometimes don’t quite understand what it means for their code to run asynchronously. But quite a bit of your code when you’re programming iOS is asynchronous, and it’s important to be clear on what this implies:
-
An NSItemProvider hands you its data asynchronously.
-
The result of requesting authorization arrives asynchronously.
-
AV Foundation properties are set asynchronously, and videos are exported asynchronously.
-
Most interactions with the photo library are asynchronous.
-
Networking is asynchronous.
And so on.
Asynchronous Code Runs Out of Order
Asynchronous code runs at an indefinite time. More important, it runs after the surrounding code. The most important thing to understand about asynchronous code is that the order in which your code appears is not the order in which it will run.
Consider the following (and see Chapter 24):
func doSomeNetworking() {
// ... prepare url ...
let session = URLSession.shared
let task = session.downloadTask(with:url) { loc, resp, err in
// ... completion function body goes here ...
}
task.resume()
}
The method downloadTask(with:completionHandler:) calls its completion function asynchronously. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access