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

# confirmMagicLink

> Completes a magic link once the user has confirmed its email address, and returns the resulting AuthResult.

**Function Signature**

```swift theme={null}
public func confirmMagicLink(_ token: String) async throws -> AuthResult
```

A `PortalAuth` method and the second of the two steps that complete a magic link. Call it only after the user has seen the email from [`getMagicLinkDetails`](./portalauthgetmagiclinkdetails) on your own screen and confirmed it is theirs: that confirmation gives the user a chance to notice someone else's link before it signs them in to the sender's account. It works only if your screen shows the email clearly and the user reads it. It exchanges the link with Portal (`POST /magic-links/validations`) and uses it up.

**Parameters**

* **`token`**: The `token` of the `.magicLink` that [`parseRedirect`](./portalauthparseredirect) returned.

**Returns**

* **`AuthResult`**: One of:
  * **`.authenticated(AuthenticatedResult)`**: The sign-in is complete. `session` is already saved to the Keychain; pass it to `Portal(credentials:)`.
  * **`.totpRequired(TotpRequiredResult)`**: A two-factor code is required. Nothing is persisted; complete the sign-in with [`verifyTotp`](./portalauthverifytotp).

**Throws**

* `PortalAuthError.invalidArgument(name: "token")`: The token is empty or whitespace-only. Raised before any network call.
* `PortalAuthError.grantRejected`: Portal refused the link: it has expired, was already used, or is otherwise unusable. Also raised without a request when the session a confirmed link signed in to has since ended. Not retryable: the user needs a new link.
* `PortalAuthError.invalidGrantResponse`: The exchange returned neither a session token nor a `userJwt`.
* `PortalAuthError.malformedResponse(path:missing:)`: The response did not carry the documented fields.
* `PortalAuthError.sessionStorageFailure(message:)`: The link was exchanged but the session could not be saved to the Keychain, so it is not returned. Call `confirmMagicLink` again with the same token on the same instance: the SDK finishes the write without sending the link again.
* Other transport errors unchanged.
* `CancellationError`: The calling task was already cancelled. Nothing is sent.

**Notes**

* Call `getMagicLinkDetails` first in any case: it also reports an expired or already used link before the user is asked to confirm. Portal does not require the lookup, and the SDK does not enforce it.
* **Exchanged successfully at most once per instance.** Concurrent calls with the same token run one at a time, so they share one successful exchange. Once a call has succeeded, calling again with the same token returns the remembered result — the same `PortalSession` instance — without a request, for as long as that session is live. That is what lets a link iOS delivers again after the user confirmed it come straight here.
* Only the most recent sign-in is remembered, on this instance and in this process, keyed by the kind of sign-in and the token. After the app is terminated, [`restoreSession`](./portalauthrestoresession) is how a completed sign-in comes back.
* A failed exchange is not remembered, so calling again sends the link again. That succeeds only if the failed attempt never reached Portal, because Portal uses up a link as soon as it receives it; otherwise it throws `.grantRejected`. The exception is `.sessionStorageFailure`, above.
* The replay stops once the remembered session has ended: after `portal.clearSession()` on a `Portal` built from that session, or a `401` it received, a repeat call throws `.grantRejected` without a request. `clearPersistedSession()` forgets the link, so a repeat call after it is sent to Portal, which rejects it with `.grantRejected`.
* On success the session is persisted **before** it is returned.
* Cancellation is honoured only before the exchange starts. Once the call has started, the exchange runs to completion even if the calling task is cancelled meanwhile, because Portal uses up the link before it answers; the result is still returned and remembered.
* A `clearPersistedSession()` called while a confirmation is in flight waits for it, then deletes the session it persisted and forgets it. The completion still returns that session to its caller, and it keeps working in memory. If your app signed out while it ran, discard the result instead of adopting it.
* A link that stopped at `.totpRequired` replays as the same step. Once `verifyTotp` accepts the code, the same link replays as the `.authenticated` result it resolved to.
* Anything you do with the result has to be safe to run twice, because a repeat call returns the same result.
* Available starting from SDK version 8.2.0.

**Example Usage**

```swift theme={null}
import PortalSwift

/// Called when the user taps Confirm on the screen that showed the link's email.
@MainActor
func confirmTapped(link: AuthRedirect.MagicLink) async {
    // One confirmation at a time, set before the first await. Disable your buttons with it.
    guard !isConfirming else { return }
    isConfirming = true
    defer { isConfirming = false }
    // Your app's count of sign-outs (PortalHolder.signOutCount in the guide).
    let signOuts = signOutCount

    do {
        let result = try await auth.confirmMagicLink(link.token)
        // Signed out while it ran: the session works in memory, but is not adopted.
        guard signOutCount == signOuts else { return }
        // Remember the link, so a copy delivered again comes straight back here.
        confirmedLink = link
        dismissConfirmation()
        switch result {
        case .authenticated(let authenticated):
            adopt(authenticated.session)
        case .totpRequired(let step):
            presentTotpPrompt(step)
        }
    } catch PortalAuthError.grantRejected {
        // Final: drop the confirmation.
        dismissConfirmation()
        showSignInError("This sign-in link can no longer be used. Request a new one.")
    } catch {
        // Keep the confirmation on screen. A retry succeeds only if this attempt never reached
        // Portal, or reached it and only the Keychain write failed (.sessionStorageFailure).
        // Otherwise it throws .grantRejected.
        showSignInError("Sign-in could not be completed. Check your connection and try again.")
    }
}
```

**Related Documentation**

* [getMagicLinkDetails reference](https://docs.portalhq.io/sdks/ios/reference/portalauthgetmagiclinkdetails.md)
* [parseRedirect reference](https://docs.portalhq.io/sdks/ios/reference/portalauthparseredirect.md)
* [verifyTotp reference](https://docs.portalhq.io/sdks/ios/reference/portalauthverifytotp.md)
* [Confirm a magic link](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#confirm-a-magic-link)
* [Handle a re-delivered redirect](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#handle-a-re-delivered-redirect)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.