### setup(projectId:with:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-singleton.md Initializes the Descope SDK with a project ID and optional configuration. This method should be called once during application startup. ```APIDOC ## setup(projectId:with:) ### Description Initializes the Descope SDK with a project ID and optional configuration. ### Parameters #### Path Parameters - **projectId** (String) - Required - The project ID found in the Descope console - **closure** ((inout DescopeConfig) -> Void) - Optional - Configuration closure to customize SDK behavior ### Returns Void ### Example ```swift import DescopeKit Descope.setup(projectId: "my-project-id") // With configuration Descope.setup(projectId: "my-project-id") { config.logger = .debugLogger config.baseURL = "https://custom-domain.descope.com" } ``` ``` -------------------------------- ### Basic Project ID Setup Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Initialize the Descope SDK with your project ID. This is the minimum required configuration. ```swift Descope.setup(projectId: "my-project-id") ``` -------------------------------- ### Setup WKWebView Configuration Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Allows direct configuration of the underlying WKWebView instance. Use this for advanced web view customizations. ```swift public static func setupWebView(_ closure: @escaping (WKWebView) -> Void) -> DescopeFlowHook ``` ```swift flow.hooks = [ .setupWebView { webView in webView.configuration.websiteDataStore = .nonPersistent() }, ] ``` -------------------------------- ### SwiftUI Session Lifecycle Example Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/session-manager.md Example of managing the Descope session lifecycle within a SwiftUI application. It handles initial setup, checking for existing sessions, and managing login/logout states. ```swift import SwiftUI @main struct MyApp: App { init() { Descope.setup(projectId: "my-project-id") } @State var isLoggedIn = false @State var user: DescopeUser? var body: some Scene { WindowGroup { if isLoggedIn { MainView(user: user) } else { LoginView(onLogin: handleLogin) } } .onAppear { checkExistingSession() } } func checkExistingSession() { if let session = Descope.sessionManager.session, !session.refreshToken.isExpired { isLoggedIn = true user = session.user } } func handleLogin(_ authResponse: AuthenticationResponse) { let session = DescopeSession(from: authResponse) Descope.sessionManager.manageSession(session) isLoggedIn = true user = session.user } } ``` -------------------------------- ### Sign Up with Details Usage Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Example of signing up a user with their email and providing additional details like name and family name. ```swift try await Descope.otp.signUp( with: .email, loginId: "user@example.com", details: SignUpDetails( name: "John Doe", givenName: "John", familyName: "Doe" ) ) ``` -------------------------------- ### Initialize SDK with Project ID (Singleton) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/README.md Use the singleton pattern for easy access to the SDK. Call `setup` with your project ID during application initialization. ```swift Descope.setup(projectId: "my-project") // Access from anywhere let session = Descope.sessionManager.session ``` -------------------------------- ### AuthenticationResponse Usage Example Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Demonstrates how to use the AuthenticationResponse after a successful OTP verification to create a DescopeSession. ```swift let authResponse = try await Descope.otp.verify(with: .email, loginId: "user@example.com", code: "123456") let session = DescopeSession(from: authResponse) ``` -------------------------------- ### OAuth Native and Web Start Usage Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Demonstrates how to initiate OAuth authentication using native providers like Apple or custom web providers. ```swift let authResponse = try await Descope.oauth.native(provider: .apple, options: []) // Or custom provider: let authResponse = try await Descope.oauth.webStart(provider: "my-custom-provider", redirectURL: nil, options: []) ``` -------------------------------- ### Basic Swift SDK Setup and Authentication Source: https://github.com/descope/descope-swift/blob/main/_autodocs/README.md Initializes the Descope SDK with a project ID, verifies a user via OTP (email), manages the session, and sets up an authenticated request header. ```swift import DescopeKit // Initialize SDK Descope.setup(projectId: "my-project-id") // Authenticate user let authResponse = try await Descope.otp.verify( with: .email, loginId: "user@example.com", code: "123456" ) // Create and manage session let session = DescopeSession(from: authResponse) Descope.sessionManager.manageSession(session) // Make authenticated requests var request = URLRequest(url: url) try await request.setAuthorizationHTTPHeaderField(from: Descope.sessionManager) let (data, _) = try await URLSession.shared.data(for: request) ``` -------------------------------- ### Dependency Injection Example Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Demonstrates how to use DescopeSDK with a dependency injection pattern, allowing for easier testing and management of dependencies in your application architecture. ```swift class AuthViewModel: ObservableObject { private let descope: DescopeSDK init(descope: DescopeSDK) { self.descope = descope } func authenticateWithOTP(loginId: String, code: String) async throws { let authResponse = try await descope.otp.verify( with: .email, loginId: loginId, code: code ) let session = DescopeSession(from: authResponse) descope.sessionManager.manageSession(session) } } // In your app initialization let descope = DescopeSDK(projectId: "my-project-id") let viewModel = AuthViewModel(descope: descope) ``` -------------------------------- ### Development Setup with Debug Logger Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Configure the Descope SDK for development environments, enabling debug logging for detailed insights. ```swift Descope.setup(projectId: "dev-project-id") { config in config.logger = .debugLogger } ``` -------------------------------- ### webStart(provider:redirectURL:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Starts an OAuth web flow and returns the authorization URL. This method is used to initiate the browser-based OAuth authentication process. ```APIDOC ## webStart(provider:redirectURL:options:) ### Description Starts an OAuth web flow, returns authorization URL. ### Method `webStart` ### Parameters #### Path Parameters - **provider** (OAuthProvider) - Required - The OAuth provider. - **redirectURL** (String?) - Optional - Custom redirect URL. Uses project default if nil. - **options** ([SignInOptions]) - Required - Custom claims, MFA, step-up, etc. ### Returns `URL` to redirect user to for authentication. ### Example ```swift let authURL = try await Descope.oauth.webStart( provider: .github, redirectURL: "myapp://oauth-callback", options: [] ) let session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: "myapp") { callbackURL, error in guard let url = callbackURL else { return } guard let code = URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems?.first(where: { $0.name == "code" })?.value else { return } Task { let authResponse = try await Descope.oauth.webExchange(code: code) // ... } } session.presentationContextProvider = self session.start() ``` ``` -------------------------------- ### Accessing Login IDs Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Get a list of identifiers the user can authenticate with. This example shows how to access the first login ID in the list. ```swift if let primaryId = session.user.loginIds.first { print("Primary login: \(primaryId)") } ``` -------------------------------- ### Start OAuth Web Flow Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Starts an OAuth web flow by returning an authorization URL. This is used to redirect the user to the OAuth provider's website for authentication. Supports custom redirect URLs and options. ```swift public func webStart(provider: OAuthProvider, redirectURL: String?, options: [SignInOptions]) async throws(DescopeError) -> URL ``` ```swift let authURL = try await Descope.oauth.webStart( provider: .github, redirectURL: "myapp://oauth-callback", options: [] ) let session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: "myapp") { callbackURL, error in guard let url = callbackURL else { return } guard let code = URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems?.first(where: { $0.name == "code" })?.value else { return } Task { let authResponse = try await Descope.oauth.webExchange(code: code) // ... } } session.presentationContextProvider = self session.start() ``` -------------------------------- ### Permission Checking Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Provides examples for checking user permissions and roles within a specific tenant. ```APIDOC ## Permission Checking ```swift func canAccessAdminPanel(user: DescopeUser, tenant: String?) -> Bool { let session = Descope.sessionManager.session! return session.permissions(tenant: tenant).contains("admin") } func isManagerInTenant(_ tenant: String, user: DescopeUser) -> Bool { let session = Descope.sessionManager.session! return session.roles(tenant: tenant).contains("manager") } ``` ``` -------------------------------- ### Get SDK Information Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Retrieves the SDK name and version. This is useful for logging or debugging purposes. ```swift public static let name = "DescopeKit" public static let version = "0.11.1" ``` ```swift print("\(DescopeSDK.name) v\(DescopeSDK.version)") // DescopeKit v0.11.1 ``` -------------------------------- ### Get Descope SDK Version Information Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Print the name and version of the Descope SDK. ```swift print(DescopeSDK.name) print(DescopeSDK.version) ``` -------------------------------- ### Start SSO/SAML Authentication Source: https://github.com/descope/descope-swift/blob/main/README.md Initiates an SSO/SAML authentication flow for a specific tenant. Generates a URL that redirects the user to the identity provider for authentication. ```swift // Choose which tenant to log into // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the SSO/SAML redirect chain let authURL = try await Descope.sso.start(emailOrTenantName: "my-tenant-ID", redirectURL: "exampleauthschema://my-app.com/handle-saml", options: []) ``` -------------------------------- ### Handling Passkey Authentication Failure Source: https://github.com/descope/descope-swift/blob/main/_autodocs/errors.md Example of catching `.passkeyFailed` during passkey sign-in, indicating a general failure in the passkey operation. ```swift do { let response = try await Descope.passkey.signIn( loginId: email, options: [] ) } catch .passkeyFailed { showAlert("Passkey authentication failed") } ``` -------------------------------- ### Production Setup with No Logging Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Configure the Descope SDK for production environments, disabling logging to minimize overhead and protect sensitive data. ```swift Descope.setup(projectId: "prod-project-id") { config in config.logger = nil // No logging } ``` -------------------------------- ### Conditional Logger Setup Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Set up logging based on the build configuration, using debug logger for debug builds and no logger for release builds. ```swift Descope.setup(projectId: "my-project") { config in #if DEBUG config.logger = .debugLogger #else config.logger = nil // No logging in release #endif } ``` -------------------------------- ### Custom Hook Example Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Demonstrates how to create a custom DescopeFlowHook by subclassing `DescopeFlowHook` and overriding the `execute` method to define custom behavior. ```APIDOC ## Custom Hooks Subclass `DescopeFlowHook` to create custom behavior: ```swift class CustomFlowHook: DescopeFlowHook { init() { super.init(events: [.ready]) } override func execute(event: Event, coordinator: DescopeFlowCoordinator) { coordinator.addStyles("body { color: blue; }") } } flow.hooks = [CustomFlowHook()] ``` ``` -------------------------------- ### Get Tenant Information Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Retrieves tenant information for the current user. Can fetch the default tenant or specific tenants by their IDs. ```swift // Get default tenant let tenants = try await Descope.auth.tenants(dct: true, tenantIds: [], refreshJwt: session.refreshJwt) // Get specific tenants let tenants = try await Descope.auth.tenants( dct: false, tenantIds: ["tenant-1", "tenant-2"], refreshJwt: session.refreshJwt ) ``` -------------------------------- ### Prompt Action Based on User Status Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Guide the user flow based on their current status (invited, enabled, disabled). ```swift func promptActionIfNeeded(user: DescopeUser) { switch user.status { case .invited: showCompleteSignupPrompt() case .enabled: // Normal flow break case .disabled: showAccountDisabledAlert() } } ``` -------------------------------- ### Custom Network Client Implementation Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Example implementation of a custom network client using URLSession for the Descope SDK. This allows for custom network request handling. ```swift class CustomNetworkClient: DescopeNetworkClient { let session: URLSession func call(request: URLRequest) async throws -> (Data, URLResponse) { return try await session.data(for: request) } } Descope.setup(projectId: "my-project") { config in config.networkClient = CustomNetworkClient(session: mySession) } ``` -------------------------------- ### Setup UIScrollView Configuration (iOS) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Allows configuration of the UIScrollView for iOS, controlling scroll behavior and indicators. This hook is specific to iOS. ```swift public static func setupScrollView(_ closure: @escaping (UIScrollView) -> Void) -> DescopeFlowHook ``` ```swift flow.hooks = [ .setupScrollView { scrollView in scrollView.showsVerticalScrollIndicator = false scrollView.isScrollEnabled = false }, ] ``` -------------------------------- ### OAuth Native with Revoke Other Sessions Usage Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Example of initiating a native OAuth flow while also opting to revoke all other existing sessions for the user. ```swift try await Descope.oauth.native( provider: .apple, options: [.revokeOtherSessions] ) ``` -------------------------------- ### Shared Network Client Setup Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Configure the SDK to use a shared URLSession instance for network requests. This is useful for managing a single session across your application. ```swift class SharedNetworkClient: DescopeNetworkClient { let session: URLSession init(session: URLSession) { self.session = session } func call(request: URLRequest) async throws -> (Data, URLResponse) { try await session.data(for: request) } } Descope.setup(projectId: "my-project") { config in config.networkClient = SharedNetworkClient(session: AppDelegate.sharedSession) } ``` -------------------------------- ### Start a Descope Flow Modally Source: https://github.com/descope/descope-swift/blob/main/README.md Use DescopeFlowViewController to present a Descope flow modally. Implement the delegate to handle the authentication response. ```swift func showLoginScreen() { let flow = DescopeFlow(url: "https://example.com/myflow") let flowViewController = DescopeFlowViewController() flowViewController.delegate = self flowViewController.start(flow: flow) navigationController?.pushViewController(flowViewController, animated: true) } func flowViewControllerDidFinish(_ controller: DescopeFlowViewController, response: AuthenticationResponse) { let session = DescopeSession(from: response) Descope.sessionManager.manageSession(session) showMainScreen() } ``` -------------------------------- ### Loading User Profile Picture Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Load and display the user's profile picture from a URL. This example assumes an asynchronous `loadImage` function. ```swift if let picURL = session.user.picture { let image = try await loadImage(from: picURL) profileImageView.image = image } ``` -------------------------------- ### DescopeSDK Initializers Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Initializes a new DescopeSDK instance. The first initializer allows for project ID and optional configuration customization, while the second is an internal initializer for explicit configuration and client setup. ```APIDOC ## init(projectId:with:) ### Description Creates a new SDK instance with a project ID and optional configuration. ### Parameters #### Path Parameters - **projectId** (String) - Required - The project ID from the Descope console - **closure** ((inout DescopeConfig) -> Void) - Optional - Configuration customization closure ### Request Example ```swift let descope = DescopeSDK(projectId: "my-project-id") // With custom configuration let descope = DescopeSDK(projectId: "my-project-id") { config.logger = .debugLogger config.baseURL = "https://custom.descope.com" config.networkClient = customNetworkClient } ``` ## init(config:client:) ### Description Creates a new SDK instance with explicit configuration and HTTP client. This is an internal initializer. ### Parameters #### Path Parameters - **config** (DescopeConfig) - Required - The SDK configuration - **client** (DescopeClient) - Required - The HTTP client for API calls ``` -------------------------------- ### Environment-Specific Descope Setup with Build Configurations Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Conditionally configure Descope based on build settings (DEBUG vs. Release) to use different project IDs, base URLs, and loggers. ```swift func setupDescope() { let config = buildConfig() Descope.setup(projectId: config.projectId) { descopeConfig in descopeConfig.baseURL = config.baseURL descopeConfig.logger = config.logger } } func buildConfig() -> Config { #if DEBUG return Config( projectId: "debug-project", baseURL: "http://localhost:3000", logger: .debugLogger ) #else return Config( projectId: "prod-project", baseURL: nil, logger: nil ) #endif } ``` -------------------------------- ### Implement Error Recovery for Specific Descope Errors Source: https://github.com/descope/descope-swift/blob/main/_autodocs/errors.md This example shows how to recover from specific Descope errors like .wrongOTPCode, .tooManyOTPAttempts, or .networkError by taking appropriate UI actions. ```swift do { try await Descope.otp.verify(with: .email, loginId: email, code: code) } catch .wrongOTPCode { codeInput.shake() showError("Invalid code") } catch .tooManyOTPAttempts { startNewOTPFlow() } catch .networkError { retryButton.isHidden = false } catch { showUnexpectedError(error) } ``` -------------------------------- ### Start Browser-Based OAuth Authentication Source: https://github.com/descope/descope-swift/blob/main/README.md Generates a URL to initiate a browser-based OAuth flow for providers like GitHub. The redirect URL can be specified or use global configuration. ```swift // Choose an oauth provider out of the supported providers // If configured globally, the redirect URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the OAuth redirect chain let authURL = try await Descope.oauth.start(provider: .github, redirectURL: "exampleauthschema://my-app.com/handle-oauth", options: []) ``` -------------------------------- ### setupWebView(_:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Provides direct access to the WKWebView instance, allowing for advanced configuration and customization of the web view's behavior and settings. ```APIDOC ## setupWebView(_:) ### Description Configures the WKWebView. ### Method `static func setupWebView(_ closure: @escaping (WKWebView) -> Void) -> DescopeFlowHook` ### Parameters #### Path Parameters - **closure** ((WKWebView) -> Void) - Required - A closure that receives the WKWebView instance for configuration. ### Request Example ```swift flow.hooks = [ .setupWebView { webView in webView.configuration.websiteDataStore = .nonPersistent() }, ] ``` ``` -------------------------------- ### Complete Authenticated API Request Function Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/urlrequest-extension.md An example function demonstrating how to create an authenticated API request using the URLRequest extension. It handles request creation, adding the authorization header with automatic refresh, and making the network call. ```swift import Foundation func makeAuthenticatedAPIRequest( to url: URL, method: String = "GET", body: Data? = nil ) async throws -> (Data, HTTPURLResponse) { // Create request var request = URLRequest(url: url) request.httpMethod = method request.httpBody = body // Add authorization header with automatic refresh try await request.setAuthorizationHTTPHeaderField(from: Descope.sessionManager) // Make request let (data, urlResponse) = try await URLSession.shared.data(for: request) guard let httpResponse = urlResponse as? HTTPURLResponse else { throw NetworkError.invalidResponse } return (data, httpResponse) } ``` -------------------------------- ### SwiftUI Login View with DescopeFlow Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Example of integrating DescopeFlowView into a SwiftUI view to handle authentication. It manages the session state and navigates to a main view upon successful login. ```swift import SwiftUI struct LoginView: View { @State var showFlow = true @State var session: DescopeSession? var body: some View { if let session = session { MainView(session: session) } else { DescopeFlowView( flow: DescopeFlow(url: "https://example.com/login"), didFinish: handleFlowComplete ) } } func handleFlowComplete(response: AuthenticationResponse) { session = DescopeSession(from: response) Descope.sessionManager.manageSession(session) } } ``` -------------------------------- ### signUpOrIn(loginId:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sign up or sign in with a passkey. This method provides a unified interface for both new and existing users to authenticate using passkeys. ```APIDOC ## signUpOrIn(loginId:options:) ### Description Sign up or sign in with passkey. ### Method `signUpOrIn` ### Parameters #### Path Parameters - **loginId** (String) - Required - The user's login ID. - **options** ([SignInOptions]) - Required - Sign-in options. ``` -------------------------------- ### Get String Description of DescopeUser Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Retrieve a string representation of the DescopeUser object, useful for debugging or logging. ```swift let description = session.user.description // Output: DescopeUser(id: "U_abc123", loginId: "user@example.com", name: "John Doe") ``` -------------------------------- ### Sign Up and Sign In with Password Source: https://github.com/descope/descope-swift/blob/main/README.md Demonstrates creating a new user with a password and subsequently signing in with the same credentials. ```swift let authResponse = try await Descope.password.signUp(loginId: "andy@example.com", password: "securePassword123!", details: SignUpDetails( name: "Andy Rhoads" )) // in another screen let authResponse = try await Descope.password.signIn(loginId: "andy@example.com", password: "securePassword123!") ``` -------------------------------- ### signUpOrIn(with:loginId:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends an OTP that works for both new and existing users, simplifying the authentication flow. ```APIDOC ## signUpOrIn(with:loginId:options:) ### Description Sends an OTP that works for both new and existing users. ### Method POST (Assumed) ### Endpoint /v1/auth/otp/signup-or-in (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (DeliveryMethod) - Required - The delivery method for the OTP (`.email`, `.sms`, or `.whatsapp`). - **loginId** (String) - Required - The user's email, phone, or custom identifier. - **options** ([SignInOptions]) - Required - Options for sign-in, such as custom claims or MFA. ### Request Example ```json { "method": "email", "loginId": "user@example.com", "options": [] } ``` ### Response #### Success Response (200) - **message** (String) - An empty response indicating the OTP was sent successfully. ``` -------------------------------- ### Get Session Description Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/session.md Retrieves a string description of the session object, including user ID and expiry information. ```swift let description = session.description // Output: DescopeSession(userId: "user123", expires: 2024-12-31 10:30:00) ``` -------------------------------- ### Basic Initialization in App Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-singleton.md Demonstrates the basic initialization of the Descope SDK within the main application struct. ```swift import DescopeKit @main struct MyApp: App { init() { Descope.setup(projectId: "") } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### signUp(loginId:password:details:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Creates a new user account with a username and password. Password must meet the project's defined policy. ```APIDOC ## signUp(loginId:password:details:) ### Description Creates a new user with a password. ### Method POST (Assumed, typically sign-up endpoints use POST) ### Endpoint /v1/auth/password/signup (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **loginId** (String) - Required - Email, phone, or username - **password** (String) - Required - User's password (must meet policy) - **details** (SignUpDetails?) - Optional - Optional user details ### Request Example ```json { "loginId": "user@example.com", "password": "SecurePassword123!", "details": {"name": "John Doe"} } ``` ### Response #### Success Response (200) - **AuthenticationResponse** - Details about the newly created user's session. ``` -------------------------------- ### signUp(loginId:details:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Creates TOTP credentials for a new user, returning a key, QR code image, and provisioning URL. ```APIDOC ## signUp(loginId:details:) ### Description Creates TOTP credentials for a new user. ### Method POST (Assumed) ### Endpoint /v1/auth/totp/signup (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **loginId** (String) - Required - The user's unique identifier. - **details** (SignUpDetails?) - Optional - Optional user details. ### Request Example ```json { "loginId": "user@example.com", "details": null } ``` ### Response #### Success Response (200) - **totpResponse** (TOTPResponse) - Contains the TOTP key, QR code image, and provisioning URL. ``` -------------------------------- ### Handling Network Errors Source: https://github.com/descope/descope-swift/blob/main/_autodocs/errors.md Example of catching a `.networkError` during an OTP sign-in attempt and displaying an alert to the user about connection issues. ```swift try await Descope.otp.signIn(with: .email, loginId: email, options: []) } catch .networkError { showAlert("No internet connection") } ``` -------------------------------- ### Testing with Custom Network Client Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Illustrates how to use a custom network client, such as a mock client, for testing purposes. This allows you to control network responses and simulate different scenarios. ```swift class MockNetworkClient: DescopeNetworkClient { func call(request: URLRequest) async throws -> (Data, URLResponse) { // Return mock data or throw errors for testing throw DescopeError.networkError } } // Use in tests let testDescope = DescopeSDK(projectId: "test") { config.networkClient = MockNetworkClient() } ``` -------------------------------- ### Sign Up with Password Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Creates a new user account with a login ID and password. The password must meet the project's defined policy. ```swift public func signUp(loginId: String, password: String, details: SignUpDetails?) async throws(DescopeError) -> AuthenticationResponse ``` ```swift let authResponse = try await Descope.password.signUp( loginId: "user@example.com", password: "SecurePassword123!", details: SignUpDetails(name: "John Doe") ) ``` -------------------------------- ### Initialize Descope SDK for Testing Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Use a mock network client and debug logger for testing purposes. ```swift let testDescope = DescopeSDK(projectId: "test-project") { config in config.networkClient = MockNetworkClient() config.logger = .debugLogger } ``` -------------------------------- ### signUp(with:loginId:details:redirectURL:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends a magic link to a new user via email or SMS to initiate the sign-up process. Requires configuration of universal links. ```APIDOC ## signUp(with:loginId:details:redirectURL:) ### Description Sends a magic link to a new user. ### Method POST (Assumed, typically sign-up endpoints use POST) ### Endpoint /v1/auth/magiclink/signup (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (DeliveryMethod) - Required - `.email` or `.sms` - **loginId** (String) - Required - Email or phone - **details** (SignUpDetails?) - Optional - Optional user details - **redirectURL** (String?) - Optional - Custom redirect URL (uses project default if not provided) ### Request Example ```json { "method": "email", "loginId": "user@example.com", "details": {"name": "John"}, "redirectURL": null } ``` ### Response #### Success Response (200) - **String** - Empty response indicating the magic link was sent. ``` -------------------------------- ### Accessing Custom Attributes Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Retrieve custom attributes defined for the user in the Descope console. This example shows how to access a 'department' attribute. ```swift if let department = session.user.customAttributes["department"] as? String { print("Department: \(department)") } ``` -------------------------------- ### Initialize SDK for Testing Source: https://github.com/descope/descope-swift/blob/main/_autodocs/README.md Create a test instance of `DescopeSDK` by providing a mock network client. This isolates the SDK for unit testing. ```swift let testSDK = DescopeSDK(projectId: "test") { config in config.networkClient = MockNetworkClient() } ``` -------------------------------- ### Show Complete Authentication Flow Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/flows.md Demonstrates how to configure and present a full Descope authentication flow. Includes SDK customization, UI hooks, OAuth, client inputs, and session handling. ```swift func showAuthenticationFlow() { let flow = DescopeFlow(url: "https://example.com/auth") // Configure custom SDK flow.descope = customSDK // Add customization hooks flow.hooks = [ .setTransparentBody, .addStyles(selector: "body", rules: ["padding: 16px"]), .setupScrollView { scrollView in scrollView.showsVerticalScrollIndicator = false }, ] // Set OAuth provider for native Sign in with Apple flow.oauthNativeProvider = .apple // Pass custom data to flow flow.clientInputs = [ "userId": userId, "theme": "dark", ] // Handle session for authenticated flows flow.sessionProvider = { [weak self] in self?.currentSession } // Present the flow let flowVC = DescopeFlowViewController() flowVC.delegate = self flowVC.start(flow: flow) navigationController?.pushViewController(flowVC, animated: true) } ``` -------------------------------- ### Get Password Policy Requirements Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Retrieves the password policy requirements for the project. Use this to inform users about password complexity rules. ```swift public func getPolicy() async throws(DescopeError) -> PasswordPolicyResponse ``` ```swift let policy = try await Descope.password.getPolicy() print("Min length: \(policy.minLength)") print("Requires uppercase: \(policy.uppercase)") ``` -------------------------------- ### Sign Up or In with Passkey Source: https://github.com/descope/descope-swift/blob/main/README.md Use this snippet to allow users to sign up or sign in using a passkey. Ensure passkey authentication is configured in the Descope console and your app has the necessary domain associations. ```swift do { showLoading(true) let authResponse = try await Descope.passkey.signUpOrIn(loginId: "andy@example.com", options: []) let session = DescopeSession(from: authResponse) Descope.sessionManager.manageSession(session) showHomeScreen() } catch .oauthNativeCancelled { showLoading(false) print("Authentication cancelled") } catch { showError(error) } ``` -------------------------------- ### Sign Up User with OTP (Email) Source: https://github.com/descope/descope-swift/blob/main/README.md Initiate a sign-up process for a user via email using OTP. A loginId is required, and optional user details can be provided. ```swift // Every user must have a loginId. All other user details are optional: try await Descope.otp.signUp(with: .email, loginId: "andy@example.com", details: SignUpDetails( name: "Andy Rhoads" )) ``` -------------------------------- ### signIn(with:loginId:redirectURL:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends a magic link to an existing user via email or SMS to initiate the sign-in process. Requires configuration of universal links. ```APIDOC ## signIn(with:loginId:redirectURL:options:) ### Description Sends a magic link to an existing user. ### Method POST (Assumed, typically sign-in endpoints use POST) ### Endpoint /v1/auth/magiclink/signin (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (DeliveryMethod) - Required - `.email` or `.sms` - **loginId** (String) - Required - Email or phone - **redirectURL** (String?) - Optional - Custom redirect URL (uses project default if not provided) - **options** ([SignInOptions]) - Required - Custom claims, MFA, step-up, etc ### Request Example ```json { "method": "email", "loginId": "user@example.com", "redirectURL": null, "options": [] } ``` ### Response #### Success Response (200) - **String** - Empty response indicating the magic link was sent. ``` -------------------------------- ### Handling Pending Enchanted Link Verification Source: https://github.com/descope/descope-swift/blob/main/_autodocs/errors.md Example of catching `.enchantedLinkPending` when checking the status of an enchanted link, indicating the user has not yet verified. ```swift do { let response = try await Descope.enchantedLink.checkForSession(pendingRef: pendingRef) } catch .enchantedLinkPending { // Keep polling or show waiting UI print("Still waiting for user to verify link") } ``` -------------------------------- ### Initialize DescopeSDK with Project ID Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Creates a new SDK instance using a project ID and an optional configuration closure for customization. This is a common way to initialize the SDK for general use. ```swift public convenience init(projectId: String, with closure: (_ config: inout DescopeConfig) -> Void = { _ in }) ``` ```swift let descope = DescopeSDK(projectId: "my-project-id") // With custom configuration let descope = DescopeSDK(projectId: "my-project-id") { config.logger = .debugLogger config.baseURL = "https://custom.descope.com" config.networkClient = customNetworkClient } ``` -------------------------------- ### signUp(with:loginId:details:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends an OTP to a new user for sign up. Supports email, SMS, and WhatsApp delivery methods. ```APIDOC ## signUp(with:loginId:details:) ### Description Sends an OTP to a new user for sign up. ### Method POST (Assumed) ### Endpoint /v1/auth/otp/signup (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (DeliveryMethod) - Required - The delivery method for the OTP (`.email`, `.sms`, or `.whatsapp`). - **loginId** (String) - Required - The user's email, phone, or custom identifier. - **details** (SignUpDetails?) - Optional - Optional user details such as name and email. ### Request Example ```json { "method": "email", "loginId": "user@example.com", "details": { "name": "John Doe" } } ``` ### Response #### Success Response (200) - **message** (String) - An empty response indicating the OTP was sent successfully. ``` -------------------------------- ### Sign Up with OTP via Email Source: https://github.com/descope/descope-swift/blob/main/README.md Initiate the OTP sign-up process by sending a code to the specified email address. Ensure the email address is valid. ```swift // sends an OTP code to the given email address try await Descope.otp.signUp(with: .email, loginId: "andy@example.com", details: nil) ``` -------------------------------- ### Getting Roles for a Tenant Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/token.md Retrieves the list of roles assigned in the token for a specific tenant. Handles both single-tenant (nil tenant) and multi-tenant scenarios. ```swift let roles = session.sessionToken.roles(tenant: nil) if roles.contains("admin") { showAdminUI() } if roles.contains("manager") { enableManagerFeatures() } ``` -------------------------------- ### Initialize SDK with Dependency Injection Source: https://github.com/descope/descope-swift/blob/main/_autodocs/README.md Initialize the `DescopeSDK` class directly for dependency injection. This allows for easier testing and management of SDK instances. ```swift let sdk = DescopeSDK(projectId: "my-project") let viewModel = AuthViewModel(sdk: sdk) ``` -------------------------------- ### Getting Permissions for a Tenant Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/token.md Retrieves the list of permissions granted in the token for a specific tenant. Handles both single-tenant (nil tenant) and multi-tenant scenarios. ```swift // Single-tenant app let permissions = session.sessionToken.permissions(tenant: nil) if permissions.contains("delete_user") { showDeleteButton() } // Multi-tenant app let tenantPermissions = session.sessionToken.permissions(tenant: "tenant-123") if tenantPermissions.contains("admin") { showAdminPanel(for: "tenant-123") } ``` -------------------------------- ### signIn(with:loginId:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends an OTP to an existing user for sign in. Supports custom claims, MFA, and step-up authentication. ```APIDOC ## signIn(with:loginId:options:) ### Description Sends an OTP to an existing user for sign in. ### Method POST (Assumed) ### Endpoint /v1/auth/otp/signin (Assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (DeliveryMethod) - Required - The delivery method for the OTP (`.email`, `.sms`, or `.whatsapp`). - **loginId** (String) - Required - The user's email, phone, or custom identifier. - **options** ([SignInOptions]) - Required - Options for sign-in, such as custom claims or MFA. ### Request Example ```json { "method": "sms", "loginId": "+1234567890", "options": [] } ``` ### Response #### Success Response (200) - **message** (String) - An empty response indicating the OTP was sent successfully. ``` -------------------------------- ### Checking Token Expiration Status Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/token.md Checks if a token has expired and provides examples for both session and refresh tokens. If a session token is expired, it attempts to refresh it. ```swift if session.sessionToken.isExpired { print("Session JWT has expired") try await Descope.sessionManager.refreshSessionIfNeeded() } if session.refreshToken.isExpired { print("Refresh token expired - user must re-authenticate") } ``` -------------------------------- ### Checking User Status Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/user.md Determine the current status of the user account. This example demonstrates conditional logic based on whether the user is enabled or invited. ```swift if session.user.status == .enabled { showMainScreen() } else if session.user.status == .invited { showCompleteSignupPrompt() } ``` -------------------------------- ### Sign Up for TOTP Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Creates TOTP credentials for a new user, returning a key, QR code image, and provisioning URL. Requires a login ID and optional user details. ```swift public func signUp(loginId: String, details: SignUpDetails?) async throws(DescopeError) -> TOTPResponse ``` ```swift let totpResponse = try await Descope.totp.signUp( loginId: "user@example.com", details: nil ) // Display totpResponse.image (QR code) to user // Or show totpResponse.provisioningURL as a clickable link ``` -------------------------------- ### Initialize DescopeSDK with Config and Client Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Creates a new SDK instance with explicit configuration and an HTTP client. This initializer is typically used for internal purposes or advanced scenarios. ```swift init(config: DescopeConfig, client: DescopeClient) ``` -------------------------------- ### signUp(loginId:details:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Creates a new passkey for a user. This method is used to register a new passkey associated with a given login ID. ```APIDOC ## signUp(loginId:details:) ### Description Creates a new passkey for a user. ### Method `signUp` ### Parameters #### Path Parameters - **loginId** (String) - Required - The user's login ID. - **details** (SignUpDetails?) - Optional - Additional sign-up details. ``` -------------------------------- ### Get User Permissions Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/session.md Retrieves a list of permissions associated with the user for a specific tenant. If no tenant ID is provided, it returns permissions for non-multi-tenant applications. ```swift let permissions = session.permissions(tenant: "tenant-1") if permissions.contains("admin") { showAdminPanel() } ``` -------------------------------- ### Configure Beta Build Settings Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Override project ID and enable debug logging for beta builds. ```swift Descope.setup(projectId: "my-project") { config in if AppConfig.isBetaBuild { config.projectId = "beta-project" config.logger = .debugLogger } } ``` -------------------------------- ### Implement Custom Authorization Middleware Source: https://github.com/descope/descope-swift/blob/main/_autodocs/README.md Extend `URLRequest` to add custom authorization headers. This example shows how to add a session token for custom backend authentication. ```swift extension URLRequest { mutating func addCustomAuth(from session: DescopeSession) { setValue(session.sessionJwt, forHTTPHeaderField: "X-Custom-Token") } } ``` -------------------------------- ### signIn(loginId:options:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Authenticates with an existing passkey. This method is used for users to log in using their previously registered passkey. ```APIDOC ## signIn(loginId:options:) ### Description Authenticates with an existing passkey. ### Method `signIn` ### Parameters #### Path Parameters - **loginId** (String) - Required - The user's login ID. - **options** ([SignInOptions]) - Required - Sign-in options. ``` -------------------------------- ### Sign Up or In with OTP Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends an OTP that works for both new and existing users. Requires a delivery method, login ID, and sign-in options. ```swift public func signUpOrIn(with method: DeliveryMethod, loginId: String, options: [SignInOptions]) async throws(DescopeError) -> String ``` -------------------------------- ### Get Current User Details Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Retrieves the current user's details using their refresh JWT. Updates the session manager with the fetched user information. ```swift let user = try await Descope.auth.me(refreshJwt: session.refreshJwt) print("User email: \(user.email ?? \"Not set\")") Descope.sessionManager.updateUser(with: user) ``` -------------------------------- ### SignIn with Step-up Authentication Usage Source: https://github.com/descope/descope-swift/blob/main/_autodocs/types.md Shows how to perform step-up authentication to verify critical operations using a refresh token. ```swift try await Descope.otp.signIn( with: .email, loginId: "user@example.com", options: [ .stepup(refreshJwt: session.refreshJwt) ] ) // Returned JWT will have su=true claim ``` -------------------------------- ### Access Instance Configuration Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Retrieve the project ID and base URL from a Descope SDK instance. ```swift let projectId = descope.config.projectId let baseURL = descope.config.baseURL ``` -------------------------------- ### Get User Roles Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/session.md Retrieves a list of role names assigned to the user within a specific tenant. If no tenant ID is provided, it returns roles for non-multi-tenant applications. ```swift let roles = session.roles(tenant: nil) if roles.contains("manager") { enableManagerFeatures() } ``` -------------------------------- ### Configure Basic Logger Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Set up a basic logger to output error and info logs to the console. This is suitable for development and debugging. ```swift config.logger = .basicLogger ``` -------------------------------- ### Sign Up with OTP (Email) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/authentication-routes.md Sends an OTP to a new user for sign up via email. Requires a login ID and optional user details. ```swift public func signUp(with method: DeliveryMethod, loginId: String, details: SignUpDetails?) async throws(DescopeError) -> String ``` ```swift try await Descope.otp.signUp( with: .email, loginId: "user@example.com", details: SignUpDetails(name: "John Doe") ) ``` -------------------------------- ### SDK Information Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-sdk.md Returns the SDK name and version. ```APIDOC ## SDK Information ### Description Returns the SDK name and version. ### Request Example ```swift print("\(DescopeSDK.name) v\(DescopeSDK.version)") // DescopeKit v0.11.1 ``` ``` -------------------------------- ### Handling No Passkeys Added Source: https://github.com/descope/descope-swift/blob/main/_autodocs/errors.md Shows how to catch `.passkeyNoneAdded` when a user attempts to sign in with a passkey but has none configured, prompting them to create one. ```swift do { try await Descope.passkey.signIn(loginId: email, options: []) } catch .passkeyNoneAdded { // User has no passkey - offer sign up or alternative auth showAlert("Please create a passkey first") } ``` -------------------------------- ### Access Singleton Configuration Source: https://github.com/descope/descope-swift/blob/main/_autodocs/configuration.md Retrieve the project ID and the full configuration object from the Descope singleton. ```swift let projectId = Descope.projectId let config = Descope.config ``` -------------------------------- ### init(from:) Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/session.md Initializes a DescopeSession from an AuthenticationResponse. This is typically used after a successful authentication flow. ```APIDOC ## init(from:) ### Description Creates a session from an authentication response. ### Method `init` ### Parameters #### Path Parameters * **response** (AuthenticationResponse) - Required - Response from any auth method ### Request Example ```swift let authResponse = try await Descope.otp.verify( with: .email, loginId: "user@example.com", code: "123456" ) let session = DescopeSession(from: authResponse) Descope.sessionManager.manageSession(session) ``` ``` -------------------------------- ### Access Configuration and Project ID Source: https://github.com/descope/descope-swift/blob/main/_autodocs/api-reference/descope-singleton.md Retrieve the current SDK configuration and project ID from the Descope singleton. ```swift let currentProjectId = Descope.projectId let config = Descope.config ```