> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portalhq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# signInWithApple

> Completes a Sign in with Apple flow end to end in a system browser sheet and returns the resulting AuthResult.

**Function Signature**

```swift theme={null}
public func signInWithApple() async throws -> AuthResult
```

A `PortalAuth` method. Fetches a fresh authorize URL, presents Apple in an `ASWebAuthenticationSession` sheet from the anchor set with `setAuthPresentationAnchor(_:)`, receives the callback inside the sheet, and exchanges the token through the same code path as [`handleRedirect`](./portalauthhandleredirect). Replay protection, persist-before-return and the two-factor branch behave identically.

**Returns**

* **`AuthResult`**: One of:
  * **`.authenticated(AuthenticatedResult)`**: The sign-in is complete. `session` is a `PortalSession` already saved to the Keychain; pass it to `Portal(credentials:)`. `clientId` and `isAccountAbstracted` describe the client Portal resolved.
  * **`.totpRequired(TotpRequiredResult)`**: The environment requires a two-factor code. Nothing is persisted; complete the sign-in with [`verifyTotp`](./portalauthverifytotp).

**Throws**

* `PortalAuthSignInError.unavailable`: No presentation anchor was set (or its window was deallocated), the `redirectUrl` is not a custom URL scheme, or the system refused to start the session.
* `PortalAuthSignInError.signInInProgress`: Another `signInWith*` call is still running.
* `PortalAuthSignInError.closed`: The user dismissed the sheet, or the calling task was cancelled.
* `PortalAuthSignInError.callbackIncomplete`: The browser returned a callback that carried no sign-in result for this instance.
* `PortalAuthError.authMethodUnavailable(.apple)`: Apple is not enabled for this auth environment.
* `PortalAuthError.authenticationFailed(error:)`: The provider sign-in failed (`oauth_failed`).
* `PortalAuthError.sessionStorageFailure(message:)`: The session could not be saved to the Keychain. The sign-in is not returned unsaved; start a new sign-in.
* `PortalRequestsError.unauthorized`: Portal refused the authorize URL request (the `redirectUrl` is not allow-listed, the Auth Environment ID is wrong, or an enabled provider is missing its credentials), or rejected the grant.
* Other `PortalAuthError` cases `handleRedirect` can throw, and transport errors unchanged.

**Notes**

* Call `setAuthPresentationAnchor(_:)` with your window before signing in. The anchor is held weakly.
* Requires a custom-scheme `redirectUrl` such as `myapp://auth/callback`. An `https://` Universal Link is not supported by `signInWith*` in this release and throws `.unavailable`; use `loginWithApple` + `handleRedirect` for that.
* The callback is matched inside the browser session and never routed through the OS URL handler, so another app that registers the same scheme cannot intercept it. This is the recommended OAuth path.
* One sign-in at a time. Both provider URLs share a single-use `state`, so a concurrent attempt throws rather than invalidating the first.
* Apple posts the result to Portal's callback URL, which you register as a Return URL on your Services ID; Portal then redirects into the sheet's callback. Your app only ever sees the final result.
* Portal identifies an end user by email. A user who picks **Hide My Email** becomes a distinct end user, with a distinct wallet, from the same person signing in with Google or a magic link. See [Apple OAuth](../../../resources/authentication/apple-oauth#how-apple-handles-email-addresses).
* Portal delivers Sign in with Apple as a web flow, so the button is your own control. Follow Apple's Human Interface Guidelines for the Sign in with Apple button. If your app also offers Google sign-in, review App Store Review Guideline 4.8 (Login Services), which may require you to offer Sign in with Apple as well.
* Cancelling the calling `Task` dismisses the sheet and throws `.closed`; the grant is never exchanged.
* Available starting from SDK version 8.0.0.

**Example Usage**

```swift theme={null}
import PortalSwift

func signInWithAppleTapped() async {
    guard let window = view.window else { return }
    auth.setAuthPresentationAnchor(window)

    do {
        switch try await auth.signInWithApple() {
        case .authenticated(let authenticated):
            let portal = try Portal(credentials: authenticated.session)
            portal.onSessionInvalidated { [weak self] in
                self?.showSignIn()
            }
            self.portal = portal
            print("Signed in as end user \(authenticated.session.endUserId)")
        case .totpRequired(let step):
            presentTotpPrompt(step)
        }
    } catch PortalAuthSignInError.closed {
        // The user dismissed the sheet.
    } catch PortalAuthSignInError.signInInProgress {
        // Ignore the extra tap.
    } catch PortalAuthError.authMethodUnavailable(let method) {
        print("\(method.rawValue) is not enabled for this auth environment.")
    } catch {
        print("Error signing in with Apple: \(error)")
    }
}
```

**Related Documentation**

* [loginWithApple reference](./portalauthloginwithapple)
* [handleRedirect reference](./portalauthhandleredirect)
* [verifyTotp reference](./portalauthverifytotp)
* [Google or Apple in a sign-in sheet](../guide/client-auth#google-or-apple-in-a-sign-in-sheet)
* [Apple OAuth](../../../resources/authentication/apple-oauth)
