Bridging `completionHandler(_:)` and `async/await`

If you have been reading or watching the Swift Evolution Proposals, you might have barely heard about continuations Continuations let you capture in a closure (in some cases) the result of a delegate callback and return it to be used as a suspension point after you have explicitly requested the value of that object.


There are many different ways to implement continuations. In the next example, I show you how I converted ASAuthorizationControllerDelegate “custom” object to be used as an asynchronous function



class SignInWithAppleService: NSObject, ASAuthorizationControllerDelegate {
//...
public func fetchAppleIDCredentials() async throws -> ASAuthorizationAppleIDCredential {
    let request = ASAuthorizationAppleIDProvider().createRequest()
    // ...
    return try await withCheckedThrowingContinuation { continuation in
        self.activeContinuation = continuationcontroller.performRequests()
        }
    }
}
// MARK: - Uselet signInWithAppleService = SignInWithAppleService()let credentials = try await signInWithAppleService.fetchAppleIDCredentials()

I left many details out, but it’s with the hope to make it an excersice for your reader. There are still many Apple APIs which were left out of the convertion batch, just like the above. You will find many methods with the new and old API declaration in your autocomplete window.