With ASWebAuthenticationSession, why does an iOS app run its web sign-in there instead of in its own WKWebView, and how does the result come back?
answer
- who owns the browser view
- existing Safari login, after a system alert
- callback URL into the completion handler
- presentationContextProvider before start()
- canceledLogin when the member backs out
basics
~20 sASWebAuthenticationSession shows the sign-in page in a secure system browser view that can reuse the user's Safari login, and the app never touches the page; the final redirect to the callback URL reaches the app's completion handler.
solid answer
~50 sA `WKWebView` belongs to the app, which can run script in it and read what the member types, and it lacks the member's Safari login. `ASWebAuthenticationSession` loads the page in a secure view the system presents, and the API hands the app only the outcome. A system alert naming the domain asks the member to continue, and unless the session is ephemeral the page can use the login Safari already holds, so a member signed in to the studio portal may not type anything. You create it with the authorization URL and a callback (a custom scheme, or from iOS 17.4 a `Callback`), set `presentationContextProvider`, and call `start()`. When the page redirects to the callback URL, the sheet closes and the completion handler gets the full URL; if the member cancels, it gets the `canceledLogin` error. Only the app that started the session receives that callback, even when another app registers the same scheme.
code
swift · 32 linesimport AuthenticationServices
import UIKit
@MainActor
final class PortalSignIn: NSObject, ASWebAuthenticationPresentationContextProviding {
private let window: UIWindow
init(window: UIWindow) { self.window = window }
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
window
}
func signIn(authorizeURL: URL, onCallback: @escaping (URL) -> Void) {
let handler: ASWebAuthenticationSession.CompletionHandler = { callbackURL, error in
if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin {
return // the member closed the sheet or declined the system alert
}
guard let callbackURL else { return }
onCallback(callbackURL) // e.g. yogastudio://auth?code=...
}
let session: ASWebAuthenticationSession
if #available(iOS 17.4, *) {
session = ASWebAuthenticationSession(
url: authorizeURL, callback: .customScheme("yogastudio"), completionHandler: handler)
} else {
session = ASWebAuthenticationSession(
url: authorizeURL, callbackURLScheme: "yogastudio", completionHandler: handler)
}
session.presentationContextProvider = self // required before start()
session.start()
}
}go deeper
Recall the three steps: create the session with a URL and a callback, set the presentation context provider, call start(), then read the callback URL or the canceledLogin error.
Explain who owns the page in each option, why the app never sees the password, and how the shared Safari login and the system alert shape what the member sees.
Show you handle every error code, keep the session long enough to cancel it, and pick the initializer by release instead of scattering scheme strings across the code.
Frame the web-view question as trust: a sign-in page inside the app's own view asks members and identity providers to trust the app with credentials it never needs.
## Why the sign-in page does not live in the app's own web view A membership app that signs people in through a studio's web portal has two ways to show that portal. It can put the page in a **`WKWebView`**, a view the app creates and controls, or it can hand the page to **`ASWebAuthenticationSession`**, the AuthenticationServices class built for exactly this job (available since iOS 12). The difference is who owns the browser: - In a `WKWebView` the app owns everything. It can inject its own scripts into the page, read the username and password fields, and see every cookie the page sets. A member has no way to tell whether the app is behaving, and the view does not share the login the member already has in Safari. - In `ASWebAuthenticationSession` the system presents a **secure browser view**. The class exposes no way to reach into the page: the app supplies the starting URL, and later receives one thing back, the **callback URL** the page redirects to when sign-in finishes. - Because the session can use the browser's existing data, a member already signed in to the portal in Safari can often finish with a single tap. Apple's header puts the member "in control of whether they want to use their existing logged-in session from Safari". The protocol argument for using the system browser at all (the native-app OAuth guidance) is covered with OAuth redirects; this question is about what the iOS API does. ## Creating and starting a session 1. Build the authorization URL. It must use `http://` or `https://`. 2. Create the session with a callback. On iOS 17.4 and later use `init(url:callback:completionHandler:)` with `.customScheme("yogastudio")` or `.https(host:path:)`. Below 17.4, use `init(url:callbackURLScheme:completionHandler:)`, which the SDK marks to be deprecated in favour of the callback initializer. 3. Set **`presentationContextProvider`** to an object adopting `ASWebAuthenticationPresentationContextProviding`, whose `presentationAnchor(for:)` returns the window the sheet should cover. 4. Call **`start()`**. It may be called only once per instance; starting a cancelled session fails, so a retry needs a new session. ## What the member sees - A system alert names the domain and asks whether to continue. Declining it ends the session. - The page loads in the secure view; the member signs in, or is already signed in through the shared login. - When the page redirects to a URL that matches the callback, the browser view dismisses itself. ## Handling the outcome The completion handler has the shape `(URL?, (any Error)?) -> Void`. Check the error first: | Result | What it means | |---|---| | a callback URL, no error | sign-in finished; parse the code or token from the URL as the provider documents | | `canceledLogin` | the member tapped Cancel or declined the system alert | | `presentationContextNotProvided` | no valid `presentationContextProvider` was set when `start()` ran | | `presentationContextInvalid` | the anchor was not eligible, for example a window that is not in a foreground scene | Apple's documentation adds one guarantee that a hand-rolled web view cannot give: the session makes sure **only the calling app's session** receives the callback, even when more than one installed app registers the same callback scheme. ## Lifetime and cancellation - For apps deploying to iOS 13 or later, the session keeps a strong reference to itself after `start()` until it has called the completion handler, so a local variable is enough. Below iOS 13 the app had to hold it. - Keeping a property anyway is still useful: `cancel()` stops the attempt and dismisses the browser view, for instance when the member leaves the screen. - `canStart` (iOS 13.4) reports whether `start()` would succeed without starting anything. ## Common mistakes in review - **Keeping a scheme string in several places.** The callback scheme, the Info.plist entry where one exists, and the redirect URI registered with the provider must agree; one constant avoids a session that never completes. - **Treating every error as a failure banner.** `canceledLogin` is a normal user choice: reset the button quietly instead of showing an error. - **Starting from the wrong window.** In a multi-window iPad app, return the window the member tapped in, not the first window the app finds; Apple's header asks for the anchor closest to where the member started sign-in. - **Reusing a session object.** A retry needs a new instance, because `start()` works only once. ## What stays outside this API `ASWebAuthenticationSession` only drives the browser leg. Generating a PKCE verifier, exchanging the code at the token endpoint and storing the tokens it returns are separate jobs: the PKCE material belongs with the OAuth protocol, and token storage belongs with Keychain Services. Keep the session code small and let those layers do their own work.
- What happens if you call start() without setting presentationContextProvider?On iOS 13 and later the session has nowhere to present its browser view. The completion handler receives the `presentationContextNotProvided` error and no sheet appears. Only apps deploying to releases before iOS 13 had the key window inferred for them.
- Do you have to keep a strong reference to the session while the member signs in?Not for apps deploying to iOS 13 or later: after `start()` the session holds a strong reference to itself until it has called the completion handler. Many apps still keep a property so they can call `cancel()` when the screen goes away.
- The member cancels and taps Sign in again. Can you call start() on the same session?No. `start()` may be called only once per instance, and calling it on a cancelled session fails. Create a new `ASWebAuthenticationSession` for every attempt.
- A WKWebView with a custom user agent is just as good for the sign-in page.
- The session hands the app Safari's cookies so it can call the portal's API itself.
- Without a presentationContextProvider the session falls back to the key window on iOS 17.
- Cancelling the sheet calls the completion handler with a nil URL and a nil error.
- Any app that registers the same custom scheme can steal the session's callback.
Assumes the iOS 27.1 SDK with an iOS 17 deployment target; the Callback initializer is iOS 17.4, so older releases use the callbackURLScheme initializer.