### Initial Project Setup Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Run this command to install all required tools, configure git hooks, and set up Xcode file templates. It also creates necessary configuration files for integration tests and example apps. ```bash make setup ``` -------------------------------- ### Complete Sign-In Flow Example in Swift Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/signin-signup.md Illustrates a comprehensive sign-in process, including starting a sign-in, sending verification codes for first and second factors, and activating the session. This example covers scenarios requiring multi-factor authentication. ```swift // 1. Start sign-in var signIn = try await clerk.auth.signIn("user@example.com") // 2. Send verification code signIn = try await signIn.sendEmailCode() // 3. User enters code signIn = try await signIn.attemptFirstFactorVerification( strategy: .emailCode, code: userProvidedCode ) // 4. Check if second factor needed if signIn.status == .needsSecondFactor { signIn = try await signIn.sendSecondFactorCode() signIn = try await signIn.attemptSecondFactorVerification( strategy: .phoneCode, code: secondFactorCode ) } // 5. Session is now active if signIn.status == .complete { let sessionId = signIn.createdSessionId try await clerk.auth.setActive(sessionId: sessionId!) } ``` -------------------------------- ### RedirectConfig Initialization Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/configuration.md Example of initializing RedirectConfig with custom redirect and callback URLs. ```swift let redirectConfig = Clerk.Options.RedirectConfig( redirectUrl: "com.myapp://oauth-callback", callbackUrlScheme: "com.myapp" ) ``` -------------------------------- ### Complete Session Management Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md A comprehensive example showing how to get the current session, check its status, retrieve tokens, access user and organization information, and handle pending tasks. It also covers revoking sessions, setting active sessions, and signing out. ```swift import ClerkKit // Get current session if let session = clerk.session { // Check session status switch session.status { case .active: print("Session is active") case .pending: print("Session pending - tasks: \(session.tasks ?? [])") case .expired: print("Session has expired") default: break } // Get session token let token = try await session.getToken() print("Session token: \(token ?? "none")") // Get custom token template let customToken = try await session.getToken( .init(template: "my_custom_template") ) // Check user information if let user = session.user { print("User: \(user.firstName ?? "Unknown")") } // Check organization if let orgId = session.lastActiveOrganizationId { print("Active org: \(orgId)") } // Check pending tasks if let tasks = session.tasks { for task in tasks { switch task { case .setupMfa: print("MFA setup required") case .resetPassword: print("Password reset required") case .chooseOrganization: print("Organization selection required") default: break } } } } // Revoke a session try await clerk.auth.revokeSession(session) // Set active session try await clerk.auth.setActive(sessionId: "sess_abc123") // Sign out try await clerk.auth.signOut(sessionId: nil) // Sign out from all sessions try await clerk.auth.signOut(sessionId: "sess_abc123") // Sign out from specific session ``` -------------------------------- ### KeychainConfig Initialization Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/configuration.md Example of initializing KeychainConfig with a custom service and access group. ```swift let keychainConfig = Clerk.Options.KeychainConfig( service: "com.myapp.clerk", accessGroup: "group.com.myapp" ) ``` -------------------------------- ### Complete Sign-Up Flow Example in Swift Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/signin-signup.md Demonstrates a full sign-up process, including creating a sign-up, updating user details, sending an email verification code, and verifying the email. This example covers the typical user registration journey. ```swift // 1. Create sign-up var signUp = try await clerk.auth.signUp( emailAddress: "user@example.com" ) // 2. Update with additional info signUp = try await signUp.update( firstName: "John", lastName: "Doe", password: "SecurePassword123!", legalAccepted: true ) // 3. Send email verification signUp = try await signUp.sendEmailCode() // 4. Verify email with code from email signUp = try await signUp.attemptEmailAddressVerification( code: userProvidedCode ) // 5. Check status switch signUp.status { case .complete: print("Sign-up complete! Session: \(signUp.createdSessionId ?? \"nil\")") case .unverified: print("More verification needed") case .missingFields: print("Missing required fields: \(signUp.unverifiedFields)") default: break } ``` -------------------------------- ### Update User Profile Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/user.md An example demonstrating how to update a user's first name, last name, and username. ```swift let updated = try await clerk.user?.update( firstName: "John", lastName: "Doe", username: "johndoe" ) ``` -------------------------------- ### Complete Session Management Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md A comprehensive example demonstrating various session management operations, including checking status, retrieving tokens, and handling pending tasks. ```APIDOC ## Complete Session Management Example ```swift import ClerkKit // Get current session if let session = clerk.session { // Check session status switch session.status { case .active: print("Session is active") case .pending: print("Session pending - tasks: \(session.tasks ?? [])") case .expired: print("Session has expired") default: break } // Get session token let token = try await session.getToken() print("Session token: \(token ?? "none")") // Get custom token template let customToken = try await session.getToken( .init(template: "my_custom_template") ) // Check user information if let user = session.user { print("User: \(user.firstName ?? "Unknown")") } // Check organization if let orgId = session.lastActiveOrganizationId { print("Active org: \(orgId)") } // Check pending tasks if let tasks = session.tasks { for task in tasks { switch task { case .setupMfa: print("MFA setup required") case .resetPassword: print("Password reset required") case .chooseOrganization: print("Organization selection required") default: break } } } } // Revoke a session try await clerk.auth.revokeSession(session) // Set active session try await clerk.auth.setActive(sessionId: "sess_abc123") // Sign out try await clerk.auth.signOut(sessionId: nil) // Sign out from all sessions try await clerk.auth.signOut(sessionId: "sess_abc123") // Sign out from specific session ``` ``` -------------------------------- ### Custom Middleware Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/configuration.md Demonstrates creating custom request and response middleware for Clerk. ```swift struct CustomHeaderMiddleware: ClerkRequestMiddleware { func prepare(_ request: inout URLRequest) async throws { request.setValue("custom-value", forHTTPHeaderField: "x-custom-header") } } struct ResponseDiagnosticsMiddleware: ClerkResponseMiddleware { func validate(_ response: HTTPURLResponse, data: Data, for request: URLRequest) async throws { // Inspect response or emit diagnostics here. } } let options = Clerk.Options( middleware: .init( request: [CustomHeaderMiddleware()], response: [ResponseDiagnosticsMiddleware()] ) ) ``` -------------------------------- ### Example Usage of GetTokenOptions Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Demonstrates how to use GetTokenOptions to retrieve a session token with a custom template or to force a fresh token by skipping the cache. ```swift // Use custom token template let options = Session.GetTokenOptions(template: "my_custom_template") let token = try await session.getToken(options) // Skip cache for guaranteed fresh token let freshOptions = Session.GetTokenOptions(skipCache: true) let freshToken = try await session.getToken(freshOptions) ``` -------------------------------- ### Start Enterprise SSO Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Starts an Enterprise Single Sign-On (SSO) flow, typically used for initiating the SSO process from a specific provider. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Start Enterprise SSO flow let result = await clerk.auth.startEnterpriseSSO(strategy: "your_enterprise_sso_provider") if result.isError { print("Failed to start Enterprise SSO: \(result.error)") } else { print("Enterprise SSO flow started successfully!") } ``` -------------------------------- ### Session with Organization Support Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Integrate organization context into session management. This example shows how to retrieve the active organization details and switch to a different organization for the current session. ```swift // Get current session with organization context if let session = clerk.session { // Retrieve active organization if let orgId = session.lastActiveOrganizationId { let org = try await clerk.organizations.get(id: orgId) print("Active org: \(org.name)") } // Switch to different organization try await clerk.auth.setActive( sessionId: session.id, organizationId: "org_xyz789" ) } ``` -------------------------------- ### Sign In and Verify Email Code Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/README.md This example demonstrates the process of signing in a user with an email, sending an email code for verification, and then attempting to verify that code. It uses Swift's async/await syntax and assumes the use of the shared Clerk instance. ```swift let signIn = try await Clerk.shared.auth.signIn("user@example.com") let updated = try await signIn.sendEmailCode() let verified = try await signIn.attemptFirstFactorVerification( strategy: .emailCode, code: userCode ) ``` -------------------------------- ### Listen to Clerk Auth Events in Swift Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/getting-started.md This example demonstrates how to listen for authentication events from Clerk. It updates a status string based on events like sign-in, sign-up, sign-out, and session changes. ```swift struct ContentView: View { @State private var authStatus: String = "Initializing..." var body: some View { VStack { Text("Auth Status: \(authStatus)") } .padding() .task { await listenToAuthEvents() } } private func listenToAuthEvents() async { for await event in Clerk.shared.auth.events { switch event { case .signInCompleted(let signIn): authStatus = "Signed in: \(signIn.id)" case .signUpCompleted(let signUp): authStatus = "Signed up: \(signUp.id)" case .signedOut: authStatus = "Signed out" case .sessionChanged(let old, let new): authStatus = "Session changed" case .tokenRefreshed: authStatus = "Token refreshed" case .accountDeleted: authStatus = "Account deleted" default: break } } } } ``` -------------------------------- ### Sign In with Email Link Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Start a magic-link sign-in flow for an email address. This prepares the email_link factor and stores the verifier locally. ```swift let signInAttempt = try await clerk.auth.signInWithEmailLink(emailAddress: "user@example.com") ``` -------------------------------- ### Session Token Flow with Caching Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Illustrates the session token retrieval flow, highlighting automatic token refresh and caching mechanisms. Demonstrates how to get a token, how subsequent calls use the cache, and how to bypass the cache when necessary. ```swift // Automatic token refresh with caching Task { // First call fetches fresh token let token1 = try await session.getToken() // Subsequent calls within TTL use cache let token2 = try await session.getToken() // Skip cache when needed let freshToken = try await session.getToken( .init(skipCache: true) ) } ``` -------------------------------- ### Complete Clerk iOS App Example Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/getting-started.md This Swift code demonstrates a full integration of Clerk into an iOS application using SwiftUI. It covers initialization, handling user authentication states (signed in/out), and basic navigation. Ensure you replace 'pk_test_...' with your actual Clerk publishable key. ```swift import ClerkKit import SwiftUI @main struct ClerkDemoApp: App { init() { Clerk.configure(publishableKey: "pk_test_...") } var body: some Scene { WindowGroup { if Clerk.shared.isLoaded { if let user = Clerk.shared.user { // User is signed in MainView() .onOpenURL { url in Task { try? await Clerk.shared.handle(url) } } } else { // User is not signed in AuthView() .onOpenURL { url in Task { try? await Clerk.shared.handle(url) } } } } else { // Clerk is still loading ProgressView() } } } } struct MainView: View { var body: some View { NavigationStack { VStack(spacing: 16) { if let user = Clerk.shared.user { Text("Welcome, \(user.firstName ?? \"User\")!") } NavigationLink("Profile") { UserProfileView() } Button("Sign Out") { Task { try? await Clerk.shared.auth.signOut() } } } .navigationTitle("Home") } } } struct AuthView: View { @State private var showSignUp = false var body: some View { NavigationStack { VStack(spacing: 16) { NavigationLink("Sign In") { SignInView() } NavigationLink("Sign Up") { SignUpView() } } .navigationTitle("Authentication") } } } ``` -------------------------------- ### Sign In with Apple View Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/getting-started.md A SwiftUI view that initiates the Sign in with Apple flow. It displays a button to start the process and shows any errors that occur. The result is handled to complete the sign-in or sign-up process. ```swift struct SignInWithAppleView: View { @State private var error: String? var body: some View { VStack(spacing: 16) { Button("Sign In with Apple") { Task { await signInWithApple() } } if let error = error { Text(error).foregroundColor(.red) } } .padding() } private func signInWithApple() async { error = nil do { let result = try await Clerk.shared.auth.signInWithApple() // Handle result - may be SignIn or SignUp if case .signIn(let signIn) = result { if signIn.status == .complete, let sessionId = signIn.createdSessionId { try await Clerk.shared.auth.setActive(sessionId: sessionId) } } } catch { error = error.localizedDescription } } } ``` -------------------------------- ### Sign In with Email Code Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Guides through the process of signing in a user using an email code verification flow. This involves initiating the sign-in, sending the code, and attempting verification. ```APIDOC ## Sign In with Email Code ### Description Initiates a sign-in process for a user via email code verification. The user will receive an email with a code that they must then enter to complete the sign-in. ### Method `clerk.auth.signIn(email: String)` followed by `signIn.sendEmailCode()` and `signIn.attemptFirstFactorVerification(strategy: .emailCode, code: String)` ### Parameters - `email` (string) - Required - The email address of the user to sign in. - `strategy` (SignIn.Strategy) - Required - The verification strategy, set to `.emailCode`. - `code` (string) - Required - The verification code received via email. ### Post-verification - `clerk.auth.setActive(sessionId: String)` - Call this after successful verification to activate the session. ``` -------------------------------- ### Fetch Test Keys (Clerk Employees Only) Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md For Clerk employees, this command fetches integration test keys from 1Password. It can automatically install the 1Password CLI if needed and requires access to Clerk's Shared vault. ```bash make fetch-test-keys ``` -------------------------------- ### reconfigure(publishableKey:options:) Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/clerk-main.md Reconfigures the shared Clerk instance with a new publishable key and options. This operation clears local state, installs the new configuration, and may require users to sign in again. It throws an error if the new configuration is invalid. ```APIDOC ## reconfigure(publishableKey:options:) ### Description Reconfigures the shared Clerk instance with a new publishable key and options. This method validates the new configuration, clears local Clerk state, and installs the new configuration on the existing shared instance. Any user currently signed in should be expected to sign in again after reconfiguration. ### Method Static Function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **publishableKey** (String) - Required - The new publishable key from your Clerk Dashboard - **options** (Clerk.Options) - Optional - Configuration options for the Clerk instance (Defaults to `.init()`) ### Response - **Clerk**: The configured shared Clerk instance. ### Throws An error if the new configuration is invalid. ### Request Example ```swift try await Clerk.reconfigure( publishableKey: selectedRegion.publishableKey, options: .init(proxyUrl: selectedRegion.proxyUrl) ) ``` ``` -------------------------------- ### Sign Up with Password and Email Verification Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Create a new user account by providing an email and password, then verify the email address with a code. The session is automatically activated upon successful sign-up. ```swift var signUp = try await clerk.auth.signUp( emailAddress: "user@example.com" ) signUp = try await signUp.update( password: "SecurePassword123!", firstName: "John", lastName: "Doe" ) signUp = try await signUp.sendEmailCode() signUp = try await signUp.attemptEmailAddressVerification(code: userCode) // Sign-up complete - session auto-activated ``` -------------------------------- ### Get Organization Roles Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Retrieves the available roles within an organization. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Assuming you have the organization ID let organizationId = "org_your_org_id" let result = await clerk.organizations.getRoles(id: organizationId) if result.isError { print("Failed to get organization roles: \(result.error)") } else if let roles = result.value { print("Organization Roles: \(roles)") } ``` -------------------------------- ### get organization by ID Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/organizations.md Retrieves a specific organization using its unique identifier. ```APIDOC ## GET /organizations/{id} ### Description Retrieves an organization by its ID. ### Method GET ### Endpoint /organizations/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The organization ID ### Response #### Success Response (200) - **Organization** (object) - The requested Organization object #### Response Example ```json { "id": "org_abc123", "name": "Acme Corporation", "slug": "acme-corp", "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### signUp Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Initiates a new user sign-up process with various optional parameters such as email, password, name, and metadata. ```APIDOC ## `signUp(emailAddress:password:firstName:lastName:username:phoneNumber:unsafeMetadata:legalAccepted:)` ### Description Creates a new sign-up attempt with the provided parameters. ### Method `signUp` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters #### Path Parameters * **emailAddress** (String?) - Optional - The user's email address * **password** (String?) - Optional - The user's password * **firstName** (String?) - Optional - The user's first name * **lastName** (String?) - Optional - The user's last name * **username** (String?) - Optional - The user's username * **phoneNumber** (String?) - Optional - The user's phone number in E.164 format * **unsafeMetadata** (JSON?) - Optional - Custom metadata to attach to the user * **legalAccepted** (Bool?) - Optional - Whether the user has accepted legal terms ### Request Example ```swift // Example usage: try await clerk.signUp(emailAddress: "test@example.com", password: "securepassword") ``` ### Response #### Success Response * Returns a `SignUp` object representing the sign-up attempt. #### Response Example ```swift // Example SignUp object structure (actual structure may vary): { "status": "pending_verification", "userId": null } ``` ### Throws An error if the sign-up creation fails. ``` -------------------------------- ### Sign Up with Email and Password Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Create a new user account by providing email and password. Optional fields like first name, last name, username, phone number, metadata, and legal acceptance can also be included. ```swift @discardableResult public func signUp( emailAddress: String? = nil, password: String? = nil, firstName: String? = nil, lastName: String? = nil, username: String? = nil, phoneNumber: String? = nil, unsafeMetadata: JSON? = nil, legalAccepted: Bool? = nil ) async throws -> SignUp ``` -------------------------------- ### Get Organization Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Retrieves details for a specific organization. Requires the organization's ID. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Assuming you have an organization ID let organizationId = "org_your_org_id" let result = await clerk.organizations.get(id: organizationId) if result.isError { print("Failed to get organization: \(result.error)") } else if let organization = result.value { print("Organization Name: \(organization.name)") } ``` -------------------------------- ### Get Session Token Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Retrieves a JWT token for the current session, which can be used for authenticating with your backend API. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Get the session token let token = await clerk.auth.getToken() if let sessionToken = token { print("Session token: \(sessionToken)") // Use this token to authenticate requests to your backend } else { print("Could not retrieve session token.") } ``` -------------------------------- ### Sign Up with Password Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Illustrates the process of signing up a new user with a password, including email verification. This covers updating user details and completing the sign-up flow. ```APIDOC ## Sign Up with Password ### Description Creates a new user account with a password and verifies their email address. This flow includes updating user profile information and sending an email verification code. ### Method `clerk.auth.signUp(emailAddress: String)` followed by `signUp.update(...)` and `signUp.sendEmailCode()` and `signUp.attemptEmailAddressVerification(code: String)` ### Parameters - `emailAddress` (string) - Required - The email address for the new user. - `password` (string) - Required - The user's chosen password. - `firstName` (string) - Optional - The user's first name. - `lastName` (string) - Optional - The user's last name. - `code` (string) - Required - The verification code received via email. ``` -------------------------------- ### Sign Up with Email and Password Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-up flow using a user's email address and password. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Sign up with email and password let result = await clerk.auth.signUp(emailAddress: "newuser@example.com", password: "secure_password") if result.isError { print("Sign up failed: \(result.error)") } else { print("Sign up successful!") } ``` -------------------------------- ### Get Session Token (Session) Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Retrieves a JWT token for the current session. This is an alternative way to access session tokens. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Get the session token from the session object if let session = clerk.session { let token = await session.getToken() if let sessionToken = token { print("Session token: \(sessionToken)") } else { print("Could not retrieve session token.") } } else { print("No active session found.") } ``` -------------------------------- ### Initialize Clerk Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Demonstrates how to initialize the Clerk SDK with a publishable key and custom options, including log level and Watch Connectivity. ```APIDOC ## Initialize Clerk ### Description Initializes the Clerk SDK with your application's publishable key and optional configuration settings. This is a prerequisite for using any other SDK functionality. ### Method `Clerk.configure()` ### Parameters - `publishableKey` (string) - Required - Your Clerk publishable key. - `options` (Clerk.Options) - Optional - Configuration options for the SDK. - `logLevel` (LogLevel) - Optional - Sets the verbosity of SDK logs. Defaults to `.info`. - `watchConnectivityEnabled` (bool) - Optional - Enables Watch Connectivity integration. Defaults to `false`. ``` -------------------------------- ### get organization memberships Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/organizations.md Retrieves a paginated list of memberships for the currently active organization. Supports filtering by query and role. ```APIDOC ## GET /organizations/{id}/memberships ### Description Retrieves the list of memberships for the currently active organization. Supports filtering by query and role. ### Method GET ### Endpoint /organizations/{id}/memberships ### Parameters #### Path Parameters - **id** (String) - Required - The organization ID #### Query Parameters - **query** (String?) - Optional - Returns members matching the given query. Checks identifiers, usernames, user IDs, and names. Supports partial matches. - **role** (String?) - Optional - Filter by roles (predefined or custom). - **page** (Int) - Optional - The 1-based page number to fetch. Defaults to 1. - **pageSize** (Int) - Optional - The maximum number of results per page. Defaults to 20. ### Response #### Success Response (200) - **ClerkPaginatedResponse** (object) - A paginated response containing OrganizationMembership objects. #### Response Example ```json { "data": [ { "id": "org_mem_abc123", "userId": "user_xyz789", "organizationId": "org_abc123", "role": "admin", "createdAt": "2023-01-01T11:00:00Z", "updatedAt": "2023-01-01T11:00:00Z" } ], "totalCount": 1, "hasNextPage": false } ``` ``` -------------------------------- ### Manual .keys.json Configuration Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Manually add a Clerk test instance publishable key to the .keys.json file if automatic fetching fails. ```json { "auth-email-code-password": { "pk": "pk_test_..." } } ``` -------------------------------- ### get organization roles Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/organizations.md Retrieves a paginated list of roles associated with an organization. You can specify the page number and the number of results per page. ```APIDOC ## GET /organizations/{id}/roles ### Description Returns a paginated response of RoleResource objects for a given organization. ### Method GET ### Endpoint /organizations/{id}/roles ### Parameters #### Path Parameters - **id** (String) - Required - The organization ID #### Query Parameters - **page** (Int) - Optional - The 1-based page number to fetch. Defaults to 1. - **pageSize** (Int) - Optional - The maximum number of results per page. Defaults to 20. ### Response #### Success Response (200) - **ClerkPaginatedResponse** (object) - A paginated response containing RoleResource objects. #### Response Example ```json { "data": [ { "id": "role_admin", "name": "Admin", "permissions": ["*"], "createdAt": "2023-01-01T10:00:00Z", "updatedAt": "2023-01-01T10:00:00Z" } ], "totalCount": 1, "hasNextPage": false } ``` ``` -------------------------------- ### Get Organization Memberships Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/organizations.md Fetch a paginated list of memberships for the current organization. Filtering by query, role, page, and page size is supported. ```swift @MainActor public func getMemberships( query: String? = nil, role: String? = nil, page: Int = 1, pageSize: Int = 20 ) async throws -> ClerkPaginatedResponse ``` -------------------------------- ### Access Clerk Environment and Options Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Shows how to access the environment configuration and options set for the Clerk SDK. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Access environment and options if let environment = clerk.environment { print("Environment ID: \(environment.id)") } if let options = clerk.options { print("Publishable Key: \(options.publishableKey)") } print("Instance Type: \(clerk.instanceType)") print("Proxy URL: \(clerk.proxyUrl ?? "N/A")") ``` -------------------------------- ### Get Organization Roles Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/organizations.md Retrieve a paginated list of roles associated with an organization. You can specify the page number and the number of results per page. ```swift @MainActor public func getRoles( page: Int = 1, pageSize: Int = 20 ) async throws -> ClerkPaginatedResponse ``` -------------------------------- ### Handling Clerk Client Errors Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/errors.md Example showing how to catch and display the message from a ClerkClientError, which indicates issues within the SDK's client-side operations. ```swift do { let signIn = try await clerk.auth.signInWithEmailLink(emailAddress: "") } catch let error as ClerkClientError { if let message = error.message { print("Client Error: \(message)") } } catch { print("Other error: \(error)") } ``` -------------------------------- ### Run E2E Tests Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Execute E2E tests using the provided make commands. Ensure test keys are fetched and available. ```bash make fetch-test-keys make test-e2e ``` -------------------------------- ### Get Session Token Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Explains how to retrieve the current session token, which can be used for making authenticated requests to your backend. Supports custom token templates. ```APIDOC ## Get Session Token ### Description Retrieves the current user's session token. This token is essential for authenticating API requests to your backend services. Custom token templates can also be requested. ### Method `session.getToken()` or `session.getToken(options: GetTokenOptions)` ### Parameters - `options` (GetTokenOptions) - Optional - Configuration for token retrieval. - `template` (string) - Optional - The name of a custom token template to use. ``` -------------------------------- ### Initialize Clerk SDK Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Configure the Clerk SDK with your publishable key and custom options. Ensure you are using Swift 6.2+ and targeting compatible OS versions. ```swift import ClerkKit @main struct MyApp: App { init() { Clerk.configure( publishableKey: "pk_test_...", options: Clerk.Options( logLevel: .debug, watchConnectivityEnabled: true ) ) } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### Get Session Token Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Retrieves the user's session token, using a cache to avoid unnecessary network requests. The token is valid for one minute. ```swift @discardableResult public func getToken(_ options: Session.GetTokenOptions = .init()) async throws -> String? ``` ```swift let token = try await clerk.auth.getToken() print("Token: \(token ?? \"nil\")") ``` -------------------------------- ### Configure Clerk SDK Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initializes and configures the Clerk SDK with your publishable key and other options. ```swift import Clerk // Configure the Clerk SDK with your publishable key let clerk = Clerk(publishableKey: "pk_test_...") // Optional: Configure other options like redirect URLs let options = Clerk.Options( redirectConfig: Clerk.Options.RedirectConfig( signInUrl: "yourapp://sign-in", signUpUrl: "yourapp://sign-up" ) ) clerk.configure(options: options) print("Clerk SDK configured.") ``` -------------------------------- ### Run E2E Tests with Custom Publishable Key Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Run E2E tests using a specific publishable key provided via an environment variable. Replace 'pk_test_...' with your actual key. ```bash CLERK_E2E_PUBLISHABLE_KEY=pk_test_... make test-e2e ``` -------------------------------- ### Handling Cancellation Errors in Async Operations Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/errors.md This example shows how to catch Swift's standard CancellationError for asynchronous operations. This is crucial for managing user-initiated cancellations or timeouts. ```swift import Foundation do { let signIn = try await clerk.auth.signIn("user@example.com") } catch is CancellationError { // Task was cancelled (e.g., user navigated away) print("Operation was cancelled") } catch { print("Error: \(error)") } ``` -------------------------------- ### Sign Up with OAuth Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-up flow using an OAuth provider (e.g., Google, Facebook). ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Sign up with Google OAuth let result = await clerk.auth.signUpWithOAuth(strategy: .google) if result.isError { print("OAuth sign up failed: \(result.error)") } else { print("OAuth sign up initiated successfully!") // The SDK will handle the redirect to the OAuth provider } ``` -------------------------------- ### Handling Clerk API Errors Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/errors.md Example demonstrating how to catch and process errors specifically of type ClerkAPIError, printing details like the error code and trace ID. ```swift do { let signIn = try await clerk.auth.signIn("user@example.com") } catch let error as ClerkAPIError { print("API Error: \(error.code)") print("Message: \(error.longMessage ?? error.message ?? "Unknown error")") if let traceId = error.clerkTraceId { print("Trace ID: \(traceId)") } } catch { print("Other error: \(error)") } ``` -------------------------------- ### Sign Up with Apple Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-up flow using Apple's Sign In with Apple service. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Sign up with Apple let result = await clerk.auth.signUpWithApple() if result.isError { print("Apple sign up failed: \(result.error)") } else { print("Apple sign up initiated successfully!") // The SDK will handle the redirect to Apple's authentication page } ``` -------------------------------- ### Run Unit and UI Tests Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Execute unit tests on macOS or UI tests on an iOS Simulator using make commands. ```bash make test # Run ClerkKitUITests on iOS Simulator make test-ui ``` -------------------------------- ### Session with Multi-Session Support Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Demonstrates how to access and manage multiple sessions for a user, including switching between them. ```APIDOC ## Session with Multi-Session Support ```swift // Access all sessions for the current user let sessions = clerk.sessionsByUserId[userId] ?? [] for session in sessions { print("Session: \(session.id)") print("Status: \(session.status)") print("Created: \(session.createdAt)") // Switch to different session if session.status == .active { try await clerk.auth.setActive(sessionId: session.id) break } } ``` ``` -------------------------------- ### Session Task Enum Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Represents pending tasks required before a session is fully active. Use this enum to identify necessary user actions like MFA setup or organization selection. ```swift public enum Task: Codable, Equatable, Hashable, Sendable ``` -------------------------------- ### Run Integration Tests Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Execute only integration tests using the make command. This is intended for Clerk employees only. ```bash make test-integration ``` -------------------------------- ### options Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/clerk-main.md Exposes the configuration options used to initialize the Clerk instance. This property reflects the settings passed during `configure` or `reconfigure`. ```APIDOC ## options ### Description The configuration options for this Clerk instance. This property reflects the settings passed during `configure` or `reconfigure`. ### Method Property Getter ### Endpoint N/A ### Parameters None ### Response - **Clerk.Options**: The configuration options for the Clerk instance. ``` -------------------------------- ### Session with Organization Support Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Illustrates how to manage session context with organizations, including retrieving the active organization and switching organizations. ```APIDOC ## Session with Organization Support ```swift // Get current session with organization context if let session = clerk.session { // Retrieve active organization if let orgId = session.lastActiveOrganizationId { let org = try await clerk.organizations.get(id: orgId) print("Active org: \(org.name)") } // Switch to different organization try await clerk.auth.setActive( sessionId: session.id, organizationId: "org_xyz789" ) } ``` ``` -------------------------------- ### Sign Up with OAuth Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Initiate an OAuth sign-up flow with a specified provider. This method is not available on tvOS or watchOS. You can optionally use an ephemeral browser session and attach custom metadata. ```swift #if !os(tvOS) && !os(watchOS) @discardableResult public func signUpWithOAuth( provider: OAuthProvider, prefersEphemeralWebBrowserSession: Bool = false, unsafeMetadata: JSON? = nil ) async throws -> TransferFlowResult #endif ``` -------------------------------- ### Get Session Token Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/session.md Retrieves the user's session token, utilizing a cache to avoid unnecessary network requests. The token's Time-To-Live (TTL) is one minute. Use custom templates for specific token requirements. ```swift @discardableResult @MainActor public func getToken(_ options: GetTokenOptions = .init()) async throws -> String? ``` ```swift let token = try await session.getToken() print("Token: \(token ?? \"nil\")") // With custom template let customToken = try await session.getToken( .init(template: "my_custom_template") ) ``` -------------------------------- ### Initialize Clerk in Your App Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/getting-started.md Initialize the Clerk SDK with your publishable key in your application's main struct. ```swift import ClerkKit @main struct MyApp: App { init() { Clerk.configure(publishableKey: "pk_test_...") } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### SignUp Object Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/types.md Represents the state of a user sign-up process, including details like ID, status, contact information, and metadata. ```APIDOC ## SignUp Object ### Description The SignUp object holds the state of a sign-up process. ### Properties - **id** (String) - Unique identifier for this sign-up - **status** (Status) - The status of the current sign-up - **emailAddress** (String?) - The email address being signed up - **phoneNumber** (String?) - The phone number being signed up - **firstName** (String?) - First name provided during sign-up - **lastName** (String?) - Last name provided during sign-up - **username** (String?) - Username provided during sign-up - **password** (String?) - Whether a password was provided - **unsafeMetadata** (JSON?) - Custom metadata attached to the sign-up - **legalAccepted** (Bool?) - Whether the user accepted legal terms - **verifications** ([String: Verification]) - Verification states for email, phone, etc. - **unverifiedFields** ([String]) - Fields that still need verification - **createdSessionId** (String?) - Session ID created upon completion - **createdUserId** (String?) - User ID created upon completion ### SignUp.Status Enum #### Description Represents the possible states of a sign-up process. #### Cases - **missingFields** - One or more required fields are missing - **unverified** - Verification is incomplete - **complete** - Sign-up process completed successfully - **abandoned** - Sign-up was abandoned - **unknown(String)** - Unknown status (raw value preserved) ``` -------------------------------- ### Sign Up with Apple Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Perform a sign-up using Apple's 'Sign in with Apple' service. You can specify requested scopes and attach custom metadata. This method is not available on watchOS or tvOS. ```swift #if !os(watchOS) && !os(tvOS) @discardableResult public func signUpWithApple( requestedScopes: [ASAuthorization.Scope] = [.email, .fullName], unsafeMetadata: JSON? = nil ) async throws -> TransferFlowResult #endif ``` -------------------------------- ### Sign In with Email Code Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Initiate a sign-in flow using an email address and send a One-Time Password (OTP) to it. ```swift let signInAttempt = try await clerk.auth.signInWithEmailCode(emailAddress: "user@example.com") ``` -------------------------------- ### Sign In with Email Link Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-in flow using an email link. The user clicks the link to complete the sign-in. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Send email link for sign in let result = await clerk.auth.signInWithEmailLink(emailAddress: "test@example.com", redirectUrl: "yourapp://callback") if result.isError { print("Failed to send email link: \(result.error)") } else { print("Email link sent successfully!") } ``` -------------------------------- ### Sign In with Email Code Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/INDEX.md Initiate a sign-in flow using an email code. This involves sending the code, verifying it with user input, and then activating the session. ```swift let signIn = try await clerk.auth.signIn("user@example.com") let updated = try await signIn.sendEmailCode() // User enters code from email let verified = try await signIn.attemptFirstFactorVerification( strategy: .emailCode, code: userProvidedCode ) if verified.status == .complete { try await clerk.auth.setActive(sessionId: verified.createdSessionId!) } ``` -------------------------------- ### Handle Transfer Flow (Sign Up) Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Handles a transfer flow during the sign-up process, potentially for migrating user data or sessions. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Handle a transfer flow during sign up let transferData = "some_transfer_data" let result = await clerk.signUp.handleTransferFlow(data: transferData) if result.isError { print("Failed to handle transfer flow: \(result.error)") } else { print("Transfer flow handled successfully!") } ``` -------------------------------- ### Sign In with Passkey Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-in flow using a Passkey. This requires the user to have a Passkey set up on their device. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Sign in with Passkey let result = await clerk.auth.signInWithPasskey() if result.isError { print("Passkey sign in failed: \(result.error)") } else { print("Passkey sign in initiated successfully!") // The device's authenticator will be invoked } ``` -------------------------------- ### Sign In with Password Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/MANIFEST.md Initiates a sign-in flow using a user's email address and password. ```swift let clerk = Clerk(publishableKey: "pk_test_...") // Sign in with email and password let result = await clerk.auth.signIn(emailAddress: "test@example.com", password: "your_password") if result.isError { print("Sign in failed: \(result.error)") } else { print("Sign in successful!") } ``` -------------------------------- ### signUpWithApple Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/auth.md Enables user sign-up using Apple's 'Sign in with Apple' service, leveraging native iOS capabilities. ```APIDOC ## `signUpWithApple(requestedScopes:unsafeMetadata:)` ### Description Signs up with Apple using Sign in with Apple. Not available on watchOS or tvOS. ### Method `signUpWithApple` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters #### Path Parameters * **requestedScopes** ([ASAuthorization.Scope]) - Optional - Default: `[.email, .fullName]` - The scopes to request from Apple * **unsafeMetadata** (JSON?) - Optional - Custom metadata to attach to the user ### Request Example ```swift // Example usage: try await clerk.signUpWithApple() ``` ### Response #### Success Response * Returns a `TransferFlowResult` that may contain a `SignIn` or `SignUp` depending on the flow. #### Response Example ```swift // Example TransferFlowResult object structure (actual structure may vary): { "flow": "sign_up", "signUp": { ... } } ``` ### Throws An error if the authentication fails. ``` -------------------------------- ### Clerk SDK Full Configuration Options Source: https://github.com/clerk/clerk-ios/blob/main/_autodocs/configuration.md Defines all configurable options for the Clerk SDK. Pass an instance to Clerk.configure to customize behavior. ```swift public init( logLevel: LogLevel = .error, telemetryEnabled: Bool = true, keychainConfig: KeychainConfig = .init(), proxyUrl: String? = nil, redirectConfig: RedirectConfig = .init(), watchConnectivityEnabled: Bool = false, loggerHandler: (@Sendable (LogEntry) -> Void)? = nil, middleware: MiddlewareConfig = .init() ) ``` -------------------------------- ### Run All Code Checks Source: https://github.com/clerk/clerk-ios/blob/main/CONTRIBUTING.md Execute both formatting and linting checks to ensure code quality before pushing. This command is suitable for CI environments. ```bash make check ```