No .cancel() on AuthorizationController environment value?

I'm implementing passkeys by following the example from the Food Truck sample project. I have nearly everything working, but there's one problem. I'm using the AuthorizationController environment value and passing that to my login and register functions, but when I call authorizationController.performAutoFillAssistedRequest, I don't see or know of any way to cancel it, so if the user tries to type in their username instead of use the autofill suggestion, the second (non-autofill) request throws the error, The operation couldn’t be completed. Request already in progress for specified application identifier. I know that ASAuthorizationController has a cancel() function, but is there any way to do this with AuthorizationController?

Answered by ForumsContributor in
Accepted Answer

If you perform the AutoFill request inside a Task, then you can cancel that task before starting a new one.

// Read the authorization controller from the SwiftUI environment
@Environment(\.authorizationController) private var authorizationController

// Store the task in a state variable
@State private var autoFillAuthorizationTask: Task<Void, Error>?

// Start the task when your view appears and stop it when it disappears
.onAppear {
    autoFillAuthorizationTask = Task {
        let result = try await authorizationController.performAutoFillAssistedRequests(/* requests */)
        try await handleAutoFillAuthorizationResult(result)
    }
}
.onDisappear {
    autoFillAuthorizationTask?.cancel()
    autoFillAuthorizationTask = nil
}

// Cancel the AutoFill task and start a new one from a Button
Button("Sign In") {
    autoFillAuthorizationTask?.cancel()
    autoFillAuthorizationTask = nil
    
    Task {
        let result = try await authorizationController.performRequests(/* requests */)
        try await handleAuthorizationResult(result)
    }
}
No .cancel() on AuthorizationController environment value?
 
 
Q