Swift Quickstart

This guide will only include the frontend integration. If you would like to also handle Session Management in your backend, select your backend technology below:


This is a quickstart guide to help you integrate Descope with your Swift application. Follow the steps below to get started.

Add the DescopeKit package

Next, we need to add the DescopeKit package (our Swift SDK) using the Swift package manager.

  • Within XCode, go to File > Add Packages and search for the URL of the git repo: https://github.com/descope/swift-sdk.
  • Then, configure your desired dependency rule and click "Add Package."

Import Frontend SDK

Next step is to import the DescopeKit package

AppDelegate.swift
import DescopeKit

Configure Descope with a custom Project ID

Configure Descope in the scene function of the SceneDelegate.swift. A Descope Project ID is required to initialize the SDK. You can find this ID on the project page in the Descope Console.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

AppDelegate.swift
import UIKit
import DescopeKit
 
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
 
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // initialize the Descope SDK before using it
        Descope.setup(projectId: "__ProjectID__")
 
        // show home screen if user is already logged in, otherwise show authentication screen
        let initialViewController: UIViewController
        if let session = Descope.sessionManager.session, !session.refreshToken.isExpired {
            initialViewController = AppInterface.homeScreen
        } else {
            initialViewController = AppInterface.authScreen
        }
 
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
 
        return true
    }
 
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // pass any incoming Universal Links to the current flow in case we're
        // using Magic Link authentication in the flows
        guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false }
        DescopeFlow.current?.resume(with: url)
        return true
    }
}

Add the Flow URL

You'll need to get your flowURL, which is the URL where your authentication flow is hosted on the web (eg. https://example.com/login).

AuthScreen.swift
let url = URL(string: "https://api.descope.com/login/\(Descope.config.projectId)?flow=sign-up-or-in")!

Call the startFlow function

The 'startFlow' function starts the authentication process with a custom flow url.

AuthScreen.swift
/// Creates a new DescopeFlowViewController, loads the flow into it, and pushes
/// it onto the navigation controller stack
func showFlow() {
    // create a new flow object
    let url = URL(string: "https://api.descope.com/login/\(Descope.config.projectId)?flow=password")!
    let flow = DescopeFlow(url: url)
 
    // create a new DescopeFlowViewController and start loading the flow
    let flowViewController = DescopeFlowViewController()
    flowViewController.delegate = self
    flowViewController.start(flow: flow)
 
    // push the view controller onto the navigation controller
    navigationController?.pushViewController(flowViewController, animated: true)
}
 
/// This action is called when the user taps the Sign In button
@IBAction func didPressSignIn() {
    print("Starting sign in with flow")
    showFlow()
}

Create a UI component to trigger the startFlow function

Here, we implement a Button that when clicked, calls the start flow function we just wrote.

AuthScreen.xib
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="5AU-rI-FZH" userLabel="Button">
    <rect key="frame" x="32" y="346" width="329" height="48"/>
    <constraints>
        <constraint firstAttribute="height" relation="greaterThanOrEqual" constant="48" id="VxW-y0-ini"/>
        <constraint firstAttribute="height" constant="48" id="vak-nB-FJq"/>
    </constraints>
    <color key="tintColor" name="AccentColor"/>
    <state key="normal" title="Button"/>
    <buttonConfiguration key="configuration" style="filled" title="Sign In">
        <fontDescription key="titleFontDescription" name="Verdana" family="Verdana" pointSize="17"/>
        <color key="baseForegroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
    </buttonConfiguration>
    <connections>
        <action selector="didPressSignIn" destination="-1" eventType="touchUpInside" id="Wa5-at-WG8"/>
    </connections>
</button>

Utilize the Swift SDK Session Management Functions

Descope provides the sessionManager to check if the user is authenticated or get user data such as email, userId, etc. You can use these to customize the user experience:

  • isAuthenticated: is user authenticated?
  • user: user object that contains all user attributes (email, name, etc.)
  • me: updates the managed session user details and returns it
  • logout: logs the user out by revoking the active session and clearing it from the session manager/Keychain storage
AuthScreen.swift
extension SimpleFlowController: DescopeFlowViewControllerDelegate {
    func flowViewControllerDidUpdateState(_ controller: DescopeFlowViewController, to state: DescopeFlowState, from previous: DescopeFlowState) {
        print("Flow state changed to \(state) from \(previous)")
    }
    
    func flowViewControllerDidBecomeReady(_ controller: DescopeFlowViewController) {
        // in this example we don't need to handle the ready event because we're
        // just showing the flow immediately without preloading it or anything
    }
    
    func flowViewControllerShouldShowURL(_ controller: DescopeFlowViewController, url: URL, external: Bool) -> Bool {
        // we return true so that the DescopeFlowViewController does its builtin behavior
        // of opening the URL in the user's default browser app
        return true
    }
    
    func flowViewControllerDidCancel(_ controller: DescopeFlowViewController) {
        // in this example the cancel button isn't shown because the DescopeFlowViewController
        // isn't at the root of its navigation controller stack, and the user can simply
        // tap the built-in Back button to leave the flow screen
    }
    
    func flowViewControllerDidFail(_ controller: DescopeFlowViewController, error: DescopeError) {
        // errors will usually be .networkError or .flowFailed
        print("Authentication failed: \(error)")
        showError(error)
    }
    
    func flowViewControllerDidFinish(_ controller: DescopeFlowViewController, response: AuthenticationResponse) {
        // authentication succeeded so we create a new DescopeSession, give it to the session
        // manager, and transition to the user to the home screen
        print("Authentication finished")
        let session = DescopeSession(from: response)
        Descope.sessionManager.manageSession(session)
        showHome()
    }
}

At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!

Continue with Backend SDK

If you would like to also handle Session Management in your backend, keep on reading by selecting your backend technology below:


Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page