Apps

Swift Concurrency Continuations: Getting Began

Apple vastly improved how one can write asynchronous code in Swift with the introduction of Swift Concurrency and the async/await API. In addition they launched the Continuation API, and you should utilize this rather than 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 an alternative of legacy patterns. You’ll study the next alongside the way in which:

  • What the Continuation API is and the way it works
  • Find out how to wrap a delegate-based API part and supply an async interface for it
  • Find out how to present an async API through an extension for parts that use completion callbacks
  • Find out how to use the async API rather than legacy patterns
Though not strictly required for this tutorial, confidence with the Swift async/await API will enable you higher perceive how the API works below the hood. Discover all of the sources on the Kodeco web site.

Getting Began

Obtain the starter venture 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 decide a picture, and it offers a picture description in return.

WhatsThat Image Classification

Right here above is Zohar, beloved Brittany Spaniel — in keeping with the classifier mannequin :]

The app makes use of one of many customary CoreML neural fashions to find out the picture’s major topic. Nevertheless, the mannequin’s willpower could possibly be incorrect, so it additionally provides a detection accuracy proportion. The upper the share, the extra possible the mannequin believes its prediction is correct.

You possibly can both use the default photographs, or you’ll be able to drag-and-drop your personal photographs into the simulator’s Images app. Both manner, you’ll see the out there photographs in WhatsThat’s picture picker.

Check out the venture file hierarchy, and also you’ll discover these core information:

  • AppMain.swift launches the SwiftUI interface.
  • Display is a gaggle containing three SwiftUI views.
  • ContentView.swift accommodates the primary app display.
  • ImageView.swift defines the picture view utilized in the primary display.
  • ImagePickerView.swift is a SwiftUI wrapper round a UIKit UIImagePickerController.

The Continuation API

As a short refresher, Swift Concurrency permits you to add async to a technique signature and name await to deal with asynchronous code. For instance, you’ll be able to write an asynchronous networking methodology like this:


// 1
personal func fetchData(url: URL) async throws -> Knowledge {

  // 2
  let (information, response) = strive await URLSession.shared.information(from: url)

  // 3
  guard let response = response as? HTTPURLResponse, response.isOk else {
    throw URLError(.badServerResponse)
  }
  return information
}

Right here’s how this works:

  1. You point out this methodology makes use of the async/await API by declaring async on its signature.
  2. The await instruction is called a “suspension level.” Right here, you inform the system to droop the tactic when await is encountered and start downloading information 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.

  • Lastly, you validate the response and return a Knowledge sort as promised by the tactic signature.
  • When working with async/await, the system robotically manages continuations for you. As a result of Swift, and UIKit particularly, 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 tasks with synchronous code defines 4 totally different features to droop the execution and create a continuation.

    • withCheckedContinuation(_:)
    • withCheckedThrowingContinuation(_:)
    • withUnsafeContinuation(_:)
    • withUnsafeThrowingContinuation(_:)

    As you’ll be able to see, the framework offers two variants of APIs of the identical features.

    • with*Continuation offers 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 find out about this later, so hold studying… ;]

    Resuming The Execution

    To renew the execution, you’re presupposed to name the continuation supplied by the operate above as soon as, and solely as soon as, through the use of one of many following continuation features:

    • resume() resumes the execution with out returning a consequence, e.g. for an async operate returning Void.
    • resume(returning:) resumes the execution returning the required argument.
    • resume(throwing:) resumes the execution throwing an exception and is used for ThrowingContinuation solely.
    • resume(with:) resumes the execution passing a Outcome object.

    Okay, that’s sufficient for idea! Let’s soar proper into utilizing the Continuation API.

    Changing Delegate-Primarily based APIs with Continuation

    You’ll first wrap a delegate-based API and supply an async interface for it.

    Have a look at the UIImagePickerController part from Apple. To deal with the asynchronicity of the interface, you set a delegate, current the picture picker after which look forward to the person to select a picture or cancel. When the person selects a picture, the framework informs the app through its delegate callback.

    Delegate Based Communication

    Though Apple now offers the PhotosPickerUI SwiftUI part, offering an async interface to UIImagePickerController remains to be related. For instance, you could must help an older iOS or could have custom-made the movement with a particular picker design you need to keep.

    The concept is so as to add a wrapper object that implements the UIImagePickerController delegate interface on one facet and presents the async API to exterior callers.

    Refactoring delegate based components with continuation

    Good day Picture Picker Service

    Add a brand new file to the Companies group and identify it ImagePickerService.swift.

    Change 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.major.debug("Consumer picked photograph")
        // 3
        continuation?.resume(returning: data[.originalImage] as? UIImage)
      }
    
      func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        Logger.major.debug("Consumer canceled selecting up photograph")
        // 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 out a picture, and as soon as they do, return it.

    Subsequent are these 4 factors of curiosity:

    1. On hitting withCheckedContinuation the execution is suspended, and a continuation is created and handed to the completion handler. On this situation, you employ the non-throwing variant as a result of the async operate pickImage() isn’t throwing.
    2. The continuation is saved within the class so you’ll be able to resume it later, as soon as the delegate returns.
    3. Then, as soon as the person selects a picture, the resume known as, passing the picture as argument.
    4. If the person cancels selecting a picture, you come back an empty picture — no less than 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:

    1. Take away the inheritance from NSObject on the ContentViewModel declaration. This isn’t required now that ImagePickerService implements UIImagePickerControllerDelegate.
    2. Delete the corresponding extension implementing UIImagePickerControllerDelegate and UINavigationControllerDelegate features, you could find it below // 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 below 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 = strive? ImageClassifierService()
    lazy var imagePickerService = ImagePickerService()
    

    Lastly, change 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 = strive? 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.major.error("Picture classification service lacking!")
          caption = "Error initializing Neural Mannequin"
          return
        }
    
        DispatchQueue.international(qos: .userInteractive).async {
          imageClassifierService.classifyImage(picture) { lead to
            let caption: String
            swap consequence {
            case .success(let classification):
              let description = classification.description
              Logger.major.debug("Picture classification consequence: (description)")
              caption = description
            case .failure(let error):
              Logger.major.error(
                "Picture classification failed with: (error.localizedDescription)"
              )
              caption = "Picture classification error"
            }
    
            DispatchQueue.major.async {
              self.caption = caption
            }
          }
        }
      }
    }
    

    Lastly, it is advisable to change the UIImagePickerController‘s delegate in ContentView.swift to level to the brand new delegate.

    To take action, change the .sheet with this:

    
    .sheet(isPresented: $contentViewModel.presentImagePicker) {
      ImagePickerView(delegate: contentViewModel.imagePickerService)
    }
    

    Construct and run. It’s best to see the picture picker working as earlier than, but it surely now makes use of a contemporary syntax that is simpler to learn.

    Continuation Checks

    Sadly, there’s an error within the code above!

    Open the Xcode Debug pane window and run the app.

    Now, decide a picture, and you need to see the corresponding classification. While you faucet Decide Picture once more to select one other picture, Xcode provides the next error:

    Continuation Leak For Reuse

    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! If you happen to neglect 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 value for the added security. As a default, favor to make use of the Checked API. If you wish to eliminate the runtime checks, use the Checked continuation throughout growth after which swap to the Unsafe when transport the app.

    Open ImagePickerService.swift, and you may see the pickImage now appears like this:

    
    func pickImage() async -> UIImage? {
      return await withCheckedContinuation { continuation in
        if self.continuation == nil {
          self.continuation = continuation
        }
      }
    }
    

    You’ll want to make two adjustments to repair the error herein.

    First, all the time assign the handed continuation, so it is advisable to 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.major.debug("Consumer picked photograph")
      continuation?.resume(returning: data[.originalImage] as? UIImage)
      // Reset continuation to nil
      continuation = nil
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
      Logger.major.debug("Consumer canceled selecting up photograph")
      continuation?.resume(returning: UIImage())
      // Reset continuation to nil
      continuation = nil
    }
    

    Construct and run and confirm that you may decide as many photographs as you want with out hitting any continuation-leak error.

    Changing Callback-Primarily based 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 part that wraps the ImageClassifierService and exposes an async API to ContentViewModel.

    On this case, although, you may also 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 strive await withCheckedThrowingContinuation { continuation in
          // 2
          classifyImage(picture) { lead to
            // 3
            if case let .success(classification) = consequence {
              continuation.resume(returning: classification)
              return
            }
          }
        }
      }
    }
    

    Here is a rundown of the code:

    1. As within the earlier case, the system blocks the execution on hitting the await withCheckedThrowingContinuation.
    2. 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 forward to the consequence.
    3. As soon as the part 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 mirror that the ImageClassifierService can throw an exception if one thing goes flawed.

    Utilizing Async ClassifyImage

    Now that ImageClassifierService helps async/await, it is time to change 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.major.error("Picture classification service lacking!")
        caption = "Error initializing Neural Mannequin"
        return
      }
    
      do {
        // 1
        let classification = strive await imageClassifierService.classifyImage(picture)
        // 2
        let classificationDescription = classification.description
        Logger.major.debug(
          "Picture classification consequence: (classificationDescription)"
        )
        // 3
        caption = classificationDescription
      } catch let error {
        Logger.major.error(
          "Picture classification failed with: (error.localizedDescription)"
        )
        caption = "Picture classification error"
      }
    }
    

    Here is what is going on on:

    1. You now name the ImageClassifierService.classifyImage(_:) operate asynchronously, which means the execution will pause till the mannequin has analyzed the picture.
    2. As soon as that occurs, the operate will resume utilizing the continuation to the code beneath the await.
    3. When you could have a classification, you should utilize that to replace caption with the classification consequence.

    Notice: In an actual app, you’d additionally need to intercept any throwing exceptions at this stage and replace the picture caption with an error message if the classification fails.

    There’s one closing change earlier than you are prepared to check the brand new code. Since classifyImage(_:) is now an async operate, it is advisable to 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’ll be able to name the async operate instantly.

    Now construct and run, strive selecting a picture yet one more time, and confirm that every little thing works as earlier than.

    Dealing With Continuation Checks … Once more?

    You are nearly there, however a couple of 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 Leak For Missed Call

    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 due to this fact 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 examine whether or not the outcomes returned within the completion handler are legitimate.

    Open the ImageClassifierService.swift file and change the prevailing code of your async throwing classifyImage(_:) (the one within the extension) with this:

    
    func classifyImage(_ picture: UIImage) async throws -> ImageClassifierService.Classification {
      return strive await withCheckedThrowingContinuation { continuation in
        classifyImage(picture) { lead to
          swap consequence {
          case .success(let classification):
            continuation.resume(returning: classification)
          case .failure(let error):
            continuation.resume(throwing: error)
          }
        }
      }
    }
    

    Right here you employ the extra continuation methodology resume(throwing:) that throws an exception within the calling methodology, passing the required error.

    As a result of the case of returning a Outcome sort is widespread, Swift additionally offers a devoted, extra compact instruction, resume(with:) permitting you to cut back what’s detailed above to this as an alternative:

    
    func classifyImage(_ picture: UIImage) async throws -> ImageClassifierService.Classification {
      return strive await withCheckedThrowingContinuation { continuation in
        classifyImage(picture) { lead to
          continuation.resume(with: consequence)
        }
      }
    }
    

    Gotta adore it! Now, construct and run and retry the movement the place the person cancels selecting a picture. This time, no warnings will likely be within the console.

    One Last Repair

    Though the warning about missing continuation is gone, some UI weirdness stays. Run the app, decide a picture, then strive selecting one other one and faucet Cancel on this second picture.

    As you see, the earlier picture is deleted, whilst you would possibly favor to keep up it if the person already chosen one.

    The ultimate repair consists of adjusting the ImagePickerService imagePickerControllerDidCancel(:) delegate methodology to return nil as an alternative of an empty picture.

    Open the file ImagePickerService.swift and make the next change.

    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
      Logger.major.debug("Consumer canceled selecting a picture")
      continuation?.resume(returning: nil)
      continuation = nil
    }

    With this final modification, if the person 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 completed! You streamlined your code and now have a constant code type in ContentViewModel.

    You began with a ContentViewModel that contained totally different code kinds and needed to conform to NSObject as a result 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 part with an object that wraps the delegate and exposes an async operate.
    • Made an async extension for completion handler-based part to permit a gradual rewrite of current components of the app.
    • Discovered the variations between utilizing Checked and Unsafe continuations and how one can deal with the corresponding examine errors.
    • Have been launched to the sorts of continuation features, together with async and async throwing.
    • Lastly, you noticed how one can resume the execution utilizing the resume directions and return a worth from a continuation context.

    It was a enjoyable run, but as all the time, that is just 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 e book.

    You possibly can obtain the whole venture utilizing the Obtain Supplies button on the high or backside of this tutorial.

    We hope you loved this tutorial. In case you have any questions, strategies, feedback or suggestions, please be a part of the discussion board dialogue beneath!

    Related Articles

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Back to top button