iOS
使用 ASWebAuthenticationSession 将 Human Token Journey 集成到您的 iOS 应用中。
ASWebAuthenticationSession 在系统管理的浏览器中启动 Human Token Journey。当旅程完成时,会话通过注册的 URL scheme 返回您的应用。
前提条件
- iOS 13 或更高版本
- Xcode 14+
AuthenticationServices框架(内置)- 您应用的唯一 URL scheme(例如
myapp)
步骤 1:定义 URL scheme
选择一个唯一的 scheme(例如 myapp)。创建流程时将其用作 callbackUri:
callbackUri: myapp://callback
步骤 2:创建演示上下文提供者
import AuthenticationServices
import UIKit
class UnicoAuthenticationController: NSObject, ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first else {
return ASPresentationAnchor()
}
return window
}
}
步骤 3:创建会话管理器
import AuthenticationServices
class AuthenticationSessionManager {
static let shared = AuthenticationSessionManager()
private var session: ASWebAuthenticationSession?
private let contextProvider = UnicoAuthenticationController()
func start(url: URL, completion: @escaping (String?) -> Void) {
let newSession = ASWebAuthenticationSession(
url: url,
callbackURLScheme: "myapp"
) { callbackURL, error in
self.session = nil
if let callbackURL = callbackURL {
let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)
let processId = components?.queryItems?.first(where: { $0.name == "id" })?.value
completion(processId)
} else {
completion(nil)
}
}
newSession.presentationContextProvider = contextProvider
newSession.prefersEphemeralWebBrowserSession = true
newSession.start()
session = newSession
}
}
步骤 4:启动旅程
guard let url = URL(string: processLink) else { return }
AuthenticationSessionManager.shared.start(url: url) { processId in
if let processId = processId {
// Journey completed — send processId to your backend via Get Process
} else {
// User canceled the session
}
}
信息
callbackURLScheme 参数仅接受 scheme 名称(myapp),不包含 ://。
文件概览
| 文件 | 用途 |
|---|---|
UnicoAuthenticationController.swift | 演示上下文提供者 |
| 会话管理器(您的视图或服务) | ASWebAuthenticationSession 生命周期 |