> ## 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.

# signInWithGoogle

> Completes a Google sign-in end to end in a system browser sheet and returns the resulting AuthResult.

**Function Signature**

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

A `PortalAuth` method. Fetches a fresh authorize URL, presents Google 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(.google)`: Google 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 `loginWithGoogle` + `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.
* Set `prefersEphemeralWebBrowserSession = true` to open the sheet without shared cookies. The default `false` lets a returning user reuse their Safari sign-in, which also means a user who signed out gets the same Google account back.
* 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 signInWithGoogleTapped() async {
    guard let window = view.window else { return }
    auth.setAuthPresentationAnchor(window)

    do {
        switch try await auth.signInWithGoogle() {
        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 Google: \(error)")
    }
}
```

**Related Documentation**

* [loginWithGoogle reference](./portalauthloginwithgoogle)
* [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)
* [Google OAuth](../../../resources/authentication/google-oauth)
