CheckedThrowingContinuation Crashes when resuming value

Hi, Our team is making 'sign with apple' with continuation to use async/await.

This is the codes we are using.

However, we encountered quite lots of crashes on continuation?.resume(returning: appleIDCredential).

final class ASAuthorizationAdapter: NSObject, ASAuthorizationControllerDelegate,
    ASAuthorizationControllerPresentationContextProviding
  {
    private var continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>?

    func signInWithApple() async throws -> ASAuthorizationAppleIDCredential {
      try await withCheckedThrowingContinuation { continuation in
        self.continuation = continuation
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
      }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
      switch authorization.credential {
      case let appleIDCredential as ASAuthorizationAppleIDCredential:
        continuation?.resume(returning: appleIDCredential)
      default:
        break
      }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
      continuation?.resume(throwing: error)
    }

    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
      (Navigator.default.topMostViewController?.view.window)!
    }
  }

The crash log says nothing about the cause of the problem.

Is There a problem we're missing? Thanks in advance.

Accepted Reply

By far the most common cause of such problems is folks resuming the same continuation twice. A good way to detect that in this case would be to nil out self.continuation when you resume it and then use self.continuation!.resume(…). That’ll trap in your code if continuation is nil, allowing you to investigate whatever logic error is causing this problem.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Replies

By far the most common cause of such problems is folks resuming the same continuation twice. A good way to detect that in this case would be to nil out self.continuation when you resume it and then use self.continuation!.resume(…). That’ll trap in your code if continuation is nil, allowing you to investigate whatever logic error is causing this problem.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks to your reply, we were able to solve the problem!!