Apple vastly improved find out how to write asynchronous code in Swift with the introduction of Swift Concurrency and the async/await API. Additionally they launched the Continuation API, and you should use this instead of delegates and completion callbacks. You possibly can vastly streamline your code by mastering and utilizing this API.
You’ll study all in regards to the Continuation API on this tutorial. Particularly, you’ll replace the tutorial app WhatsApp to make use of the Continuation API as a substitute of legacy patterns. You’ll study the next alongside the way in which:
- What the Continuation API is and the way it works
- Methods to wrap a delegate-based API element and supply an async interface for it
- Methods to present an async API through an extension for parts that use completion callbacks
- Methods to use the async API instead of legacy patterns
Getting Began
Obtain the starter challenge by clicking the Obtain Supplies button on the high or backside of this tutorial.
Open WhatsThat from the starter folder, and construct and run.
WhatsThat is an image-classifier app. You choose a picture, and it supplies a picture description in return.
Right here above is Zohar, beloved Brittany Spaniel — in response to the classifier mannequin :]
The app makes use of one of many customary CoreML neural fashions to find out the picture’s principal topic. Nonetheless, the mannequin’s dedication may very well be incorrect, so it additionally provides a detection accuracy proportion. The upper the proportion, the extra seemingly the mannequin believes its prediction is correct.
You possibly can both use the default pictures, or you possibly can drag-and-drop your individual pictures into the simulator’s Pictures app. Both method, you’ll see the obtainable pictures in WhatsThat’s picture picker.
Check out the challenge file hierarchy, and also you’ll discover these core recordsdata:
-
AppMain.swift
launches the SwiftUI interface. -
Display screen
is a gaggle containing three SwiftUI views. -
ContentView.swift
comprises the principle app display. -
ImageView.swift
defines the picture view utilized in the principle display. -
ImagePickerView.swift
is a SwiftUI wrapper round a UIKitUIImagePickerController
.
The Continuation API
As a short refresher, Swift Concurrency lets you add async
to a technique signature and name await
to deal with asynchronous code. For instance, you possibly can write an asynchronous networking technique like this:
// 1
personal func fetchData(url: URL) async throws -> Information {
// 2
let (knowledge, response) = attempt await URLSession.shared.knowledge(from: url)
// 3
guard let response = response as? HTTPURLResponse, response.isOk else {
throw URLError(.badServerResponse)
}
return knowledge
}
Right here’s how this works:
- You point out this technique makes use of the async/await API by declaring
async
on its signature. - The
await
instruction is named a “suspension level.” Right here, you inform the system to droop the strategy whenawait
is encountered and start downloading knowledge on a distinct thread.
Swift shops the state of the present operate in a heap, making a “continuation.” Right here, as soon as URLSession
finishes downloading the info, the continuation is resumed, and the execution continues from the place it was stopped.
response
and return a Information
sort as promised by the strategy signature.When working with async/await, the system robotically manages continuations for you. As a result of Swift, and UIKit specifically, closely use delegates and completion callbacks, Apple launched the Continuation API that will help you transition current code utilizing an async interface. Let’s go over how this works intimately.
Suspending The Execution
SE-0300: Continuations for interfacing async duties with synchronous code defines 4 totally different capabilities to droop the execution and create a continuation.
withCheckedContinuation(_:)
withCheckedThrowingContinuation(_:)
withUnsafeContinuation(_:)
withUnsafeThrowingContinuation(_:)
As you possibly can see, the framework supplies two variants of APIs of the identical capabilities.
-
with*Continuation
supplies a non-throwing context continuation -
with*ThrowingContinuation
additionally permits throwing exceptions within the continuations
The distinction between Checked
and Unsafe
lies in how the API verifies correct use of the resume operate. You’ll study this later, so hold studying… ;]
Resuming The Execution
To renew the execution, you’re speculated to name the continuation offered by the operate above as soon as, and solely as soon as, through the use of one of many following continuation
capabilities:
-
resume()
resumes the execution with out returning a end result, e.g. for an async operate returningVoid
. -
resume(returning:)
resumes the execution returning the required argument. -
resume(throwing:)
resumes the execution throwing an exception and is used forThrowingContinuation
solely. -
resume(with:)
resumes the execution passing aConsequence
object.
Okay, that’s sufficient for principle! Let’s bounce proper into utilizing the Continuation API.
Changing Delegate-Based mostly APIs with Continuation
You’ll first wrap a delegate-based API and supply an async interface for it.
Have a look at the UIImagePickerController
element from Apple. To deal with the asynchronicity of the interface, you set a delegate, current the picture picker after which look ahead to the consumer to choose a picture or cancel. When the consumer selects a picture, the framework informs the app through its delegate callback.
Regardless that Apple now supplies the PhotosPickerUI
SwiftUI element, offering an async interface to UIImagePickerController
continues to be related. For instance, it’s possible you’ll have to assist an older iOS or could have personalized the circulate with a particular picker design you need to preserve.
The concept is so as to add a wrapper object that implements the UIImagePickerController
delegate interface on one aspect and presents the async API to exterior callers.
Hi there Picture Picker Service
Add a brand new file to the Companies group and title it ImagePickerService.swift.
Substitute the content material of ImagePickerService.swift
with this:
import OSLog
import UIKit.UIImage
class ImagePickerService: NSObject {
personal var continuation: CheckedContinuation<UIImage?, By no means>?
func pickImage() async -> UIImage? {
// 1
return await withCheckedContinuation { continuation in
if self.continuation == nil {
// 2
self.continuation = continuation
}
}
}
}
// MARK: - Picture Picker Delegate
extension ImagePickerService: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo data: [UIImagePickerController.InfoKey: Any]
) {
Logger.principal.debug("Consumer picked picture")
// 3
continuation?.resume(returning: data[.originalImage] as? UIImage)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
Logger.principal.debug("Consumer canceled selecting up picture")
// 4
continuation?.resume(returning: UIImage())
}
}
First, you’ll discover the pickImage()
operate is async as a result of it wants to attend for customers to pick a picture, and as soon as they do, return it.
Subsequent are these 4 factors of curiosity:
- On hitting
withCheckedContinuation
the execution is suspended, and a continuation is created and handed to the completion handler. On this situation, you utilize the non-throwing variant as a result of the async operatepickImage()
isn’t throwing. - The
continuation
is saved within the class so you possibly can resume it later, as soon as the delegate returns. - Then, as soon as the consumer selects a picture, the
resume
is named, passing the picture as argument. - If the consumer cancels selecting a picture, you come back an empty picture — at the least for now.
As soon as the execution is resumed, the picture returned from the continuation is returned to the caller of the pickImage()
operate.
Utilizing Picture Picker Service
Open ContentViewModel.swift
, and modify it as follows:
- Take away the inheritance from
NSObject
on theContentViewModel
declaration. This isn’t required now thatImagePickerService
implementsUIImagePickerControllerDelegate
. - Delete the corresponding extension implementing
UIImagePickerControllerDelegate
andUINavigationControllerDelegate
capabilities, you could find it underneath// MARK: - Picture Picker Delegate
. Once more, these aren't required anymore for a similar purpose.
Then, add a property for the brand new service named imagePickerService
underneath your noImageCaption
and imageClassifierService
variables. You may find yourself with these three variables within the high of ContentViewModel
:
personal static let noImageCaption = "Choose a picture to categorise"
personal lazy var imageClassifierService = attempt? ImageClassifierService()
lazy var imagePickerService = ImagePickerService()
Lastly, substitute the earlier implementation of pickImage()
with this one:
@MainActor
func pickImage() {
presentImagePicker = true
Process(precedence: .userInitiated) {
let picture = await imagePickerService.pickImage()
presentImagePicker = false
if let picture {
self.picture = picture
classifyImage(picture)
}
}
}
As pickImage()
is a synchronous operate, you could use a Process
to wrap the asynchronous content material. Since you’re coping with UI right here, you create the duty with a userInitiated
precedence.
The @MainActor
attribute can also be required since you’re updating the UI, self.picture
right here.
After all of the adjustments, your ContentViewModel
ought to appear like this:
class ContentViewModel: ObservableObject {
personal static let noImageCaption = "Choose a picture to categorise"
personal lazy var imageClassifierService = attempt? ImageClassifierService()
lazy var imagePickerService = ImagePickerService()
@Revealed var presentImagePicker = false
@Revealed personal(set) var picture: UIImage?
@Revealed personal(set) var caption = noImageCaption
@MainActor
func pickImage() {
presentImagePicker = true
Process(precedence: .userInitiated) {
let picture = await imagePickerService.pickImage()
presentImagePicker = false
if let picture {
self.picture = picture
classifyImage(picture)
}
}
}
personal func classifyImage(_ picture: UIImage) {
caption = "Classifying..."
guard let imageClassifierService else {
Logger.principal.error("Picture classification service lacking!")
caption = "Error initializing Neural Mannequin"
return
}
DispatchQueue.world(qos: .userInteractive).async {
imageClassifierService.classifyImage(picture) { lead to
let caption: String
change end result {
case .success(let classification):
let description = classification.description
Logger.principal.debug("Picture classification end result: (description)")
caption = description
case .failure(let error):
Logger.principal.error(
"Picture classification failed with: (error.localizedDescription)"
)
caption = "Picture classification error"
}
DispatchQueue.principal.async {
self.caption = caption
}
}
}
}
}
Lastly, you could change the UIImagePickerController
‘s delegate in ContentView.swift to level to the brand new delegate.
To take action, substitute the .sheet
with this:
.sheet(isPresented: $contentViewModel.presentImagePicker) {
ImagePickerView(delegate: contentViewModel.imagePickerService)
}
Construct and run. You need to see the picture picker working as earlier than, however it now makes use of a contemporary syntax that is simpler to learn.
Continuation Checks
Sadly, there may be an error within the code above!
Open the Xcode Debug pane window and run the app.
Now, choose a picture, and it’s best to see the corresponding classification. If you faucet Decide Picture once more to choose one other picture, Xcode provides the next error:
Swift prints this error as a result of the app is reusing a continuation already used for the primary picture, and the usual explicitly forbids this! Keep in mind, you could use a continuation as soon as, and solely as soon as.
When utilizing the Checked
continuation, the compiler provides code to implement this rule. When utilizing the Unsafe
APIs and also you name the resume greater than as soon as, nonetheless, the app will crash! Should you overlook to name it in any respect, the operate by no means resumes.
Though there should not be a noticeable overhead when utilizing the Checked
API, it is definitely worth the worth for the added security. As a default, desire to make use of the Checked
API. If you wish to eliminate the runtime checks, use the Checked
continuation throughout improvement after which change to the Unsafe
when delivery the app.
Open ImagePickerService.swift, and you will see the pickImage
now appears to be like like this:
func pickImage() async -> UIImage? {
return await withCheckedContinuation { continuation in
if self.continuation == nil {
self.continuation = continuation
}
}
}
It’s essential make two adjustments to repair the error herein.
First, all the time assign the handed continuation, so you could take away the if
assertion, ensuing on this:
func pickImage() async -> UIImage? {
await withCheckedContinuation { continuation in
self.continuation = continuation
}
}
Second, set the set the continuation to nil
after utilizing it:
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo data: [UIImagePickerController.InfoKey: Any]
) {
Logger.principal.debug("Consumer picked picture")
continuation?.resume(returning: data[.originalImage] as? UIImage)
// Reset continuation to nil
continuation = nil
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
Logger.principal.debug("Consumer canceled selecting up picture")
continuation?.resume(returning: UIImage())
// Reset continuation to nil
continuation = nil
}
Construct and run and confirm that you may choose as many pictures as you want with out hitting any continuation-leak error.
Changing Callback-Based mostly APIs with Continuation
Time to maneuver on and modernize the remaining a part of ContentViewModel
by changing the completion handler within the classifyImage(:)
operate with a sleeker async name.
As you probably did for refactoring UIImagePickerController
, you may create a wrapper element that wraps the ImageClassifierService
and exposes an async API to ContentViewModel
.
On this case, although, it’s also possible to lengthen the ImageClassifier
itself with an async extension.
Open ImageClassifierService.swift and add the next code on the finish:
// MARK: - Async/Await API
extension ImageClassifierService {
func classifyImage(_ picture: UIImage) async throws -> ImageClassifierService.Classification {
// 1
return attempt await withCheckedThrowingContinuation { continuation in
// 2
classifyImage(picture) { lead to
// 3
if case let .success(classification) = end result {
continuation.resume(returning: classification)
return
}
}
}
}
}
Here is a rundown of the code:
- As within the earlier case, the system blocks the execution on hitting the
await withCheckedThrowingContinuation
. - You needn’t retailer the continuation as within the earlier case since you’ll use it within the completion handler. Simply name the outdated callback-based API and look ahead to the end result.
- As soon as the element invokes the completion callback, you name
continuation.resume<(returning:)
passing again the classification obtained.
Including an extension to the outdated interface permits use of the 2 APIs concurrently. For instance, you can begin writing new code utilizing the async/await API with out having to rewrite current code that also makes use of the completion callback API.
You utilize a Throwing
continuation to replicate that the ImageClassifierService
can throw an exception if one thing goes improper.
Utilizing Async ClassifyImage
Now that ImageClassifierService
helps async/await, it is time to substitute the outdated implementation and simplify the code. Open ContentViewModel.swift and alter the classifyImage(_:)
operate to this:
@MainActor
personal func classifyImage(_ picture: UIImage) async {
guard let imageClassifierService else {
Logger.principal.error("Picture classification service lacking!")
caption = "Error initializing Neural Mannequin"
return
}
do {
// 1
let classification = attempt await imageClassifierService.classifyImage(picture)
// 2
let classificationDescription = classification.description
Logger.principal.debug(
"Picture classification end result: (classificationDescription)"
)
// 3
caption = classificationDescription
} catch let error {
Logger.principal.error(
"Picture classification failed with: (error.localizedDescription)"
)
caption = "Picture classification error"
}
}
Here is what is going on on:
- You now name the
ImageClassifierService.classifyImage(_:)
operate asynchronously, which means the execution will pause till the mannequin has analyzed the picture. - As soon as that occurs, the operate will resume utilizing the continuation to the code under the
await.
- When you’ve gotten a classification, you should use that to replace
caption
with the classification end result.
Notice: In an actual app, you’d additionally need to intercept any throwing exceptions at this degree and replace the picture caption with an error message if the classification fails.
There’s one last change earlier than you are prepared to check the brand new code. Since classifyImage(_:)
is now an async
operate, you could name it utilizing await
.
Nonetheless in ContentViewModel.swift, within the pickImage
operate, add the await
key phrase earlier than calling the classifyImage(_:)
operate.
@MainActor
func pickImage() {
presentImagePicker = true
Process(precedence: .userInitiated) {
let picture = await imagePickerService.pickImage()
presentImagePicker = false
if let picture {
self.picture = picture
await classifyImage(picture)
}
}
}
Since you’re already in a Process
context, you possibly can name the async operate straight.
Now construct and run, attempt selecting a picture yet another time, and confirm that all the pieces works as earlier than.
Dealing With Continuation Checks … Once more?
You are nearly there, however just a few issues stay to care for. :]
Open the Xcode debug space to see the app’s logs, run and faucet Decide Picture; this time, nonetheless, faucet Cancel and see what occurs within the logs window.
Continuation checks? Once more? Did not you repair this already?
Nicely, that was a distinct situation. Here is what’s occurring this time.
When you faucet Cancel, ImagePickerService
returns an empty UIImage
, which causes CoreML to throw an exception, not managed in ImageClassificationService
.
Opposite to the earlier case, this continuation’s resume
isn’t known as, and the code subsequently by no means returns.
To repair this, head again to the ImageClassifierService
and modify the async wrapper to handle the case the place the mannequin throws an exception. To take action, you could test whether or not the outcomes returned within the completion handler are legitimate.
Open the ImageClassifierService.swift file and substitute the prevailing code of your async throwing classifyImage(_:)
(the one within the extension) with this:
func classifyImage(_ picture: UIImage) async throws -> ImageClassifierService.Classification {
return attempt await withCheckedThrowingContinuation { continuation in
classifyImage(picture) { lead to
change end result {
case .success(let classification):
continuation.resume(returning: classification)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
Right here you utilize the extra continuation technique resume(throwing:)
that throws an exception within the calling technique, passing the required error
.
As a result of the case of returning a Consequence
sort is widespread, Swift additionally supplies a devoted, extra compact instruction, resume(with:)
permitting you to cut back what’s detailed above to this as a substitute:
func classifyImage(_ picture: UIImage) async throws -> ImageClassifierService.Classification {
return attempt await withCheckedThrowingContinuation { continuation in
classifyImage(picture) { lead to
continuation.resume(with: end result)
}
}
}
Gotta find it irresistible! Now, construct and run and retry the circulate the place the consumer cancels selecting a picture. This time, no warnings will probably be within the console.
One Closing Repair
Though the warning about missing continuation is gone, some UI weirdness stays. Run the app, choose a picture, then attempt selecting one other one and faucet Cancel on this second picture.
As you see, the earlier picture is deleted, whilst you would possibly desire to keep up it if the consumer already chosen one.
The ultimate repair consists of fixing the ImagePickerService
imagePickerControllerDidCancel(:)
delegate technique to return nil
as a substitute of an empty picture.
Open the file ImagePickerService.swift and make the next change.
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
Logger.principal.debug("Consumer canceled selecting a picture")
continuation?.resume(returning: nil)
continuation = nil
}
With this final modification, if the consumer cancels selecting up a picture, the pickImage()
operate of ImagePickerService
returns nil, which means ContentViewModel
will skip setting the picture and calling classifyImage(_:)
in any respect.
Construct and run one final time and confirm the bug is gone.
The place to Go From Right here?
Nicely finished! You streamlined your code and now have a constant code fashion in ContentViewModel
.
You began with a ContentViewModel
that contained totally different code types and needed to conform to NSObject
because of delegate necessities. Little by little, you refactored this to have a contemporary and easier-to-follow implementation utilizing the async/await Continuation API.
Particularly, you:
- Changed the delegate-based element with an object that wraps the delegate and exposes an async operate.
- Made an async extension for completion handler-based element to permit a gradual rewrite of current components of the app.
- Discovered the variations between utilizing
Checked
andUnsafe
continuations and find out how to deal with the corresponding test errors. - Have been launched to the kinds of continuation capabilities, together with async and async throwing.
- Lastly, you noticed find out how to resume the execution utilizing the
resume
directions and return a price from a continuation context.
It was a enjoyable run, but as all the time, that is only the start of the journey. :]
To study extra in regards to the Continuation API and the main points of the Swift Concurrency APIs, have a look at the Fashionable Concurrency in Swift ebook.
You possibly can obtain the entire challenge utilizing the Obtain Supplies button on the high or backside of this tutorial.
We hope you loved this tutorial. If in case you have any questions, ideas, feedback or suggestions, please be a part of the discussion board dialogue under!