Compartir vía


iOS SDK Installation

SDK Initialization

Important

  • Currently, Clarity SDK mainly supports UIKit-based applications. As a result, Clarity cannot capture most views from SwiftUI-based applications unless enableSwiftUI_Experimental flag is set to true. It is strongly recommended to review the SwiftUI Modifiers section beforehand for detailed guidance.
  • The Clarity SDK supports iOS version 15-18 inclusive. While applications build and run successfully for iOS versions 13-14 inclusive, data isn't sent to Clarity.

Install the Clarity SDK in order to track how users interact with your app. The Clarity iOS SDK is available as a Swift package and a CocoaPods pod. It can take up to 2 hours to start seeing data.

Step 1

Option 1: Using XCode

  1. "Right click" on your XCode project and select Add Package Dependencies...
  2. Paste https://github.com/microsoft/clarity-apps in the search bar, select clarity-apps, and select Add Package.

Option 2: If the Package.swift file is used, add Clarity package as a dependency:

let package = Package(
    // ...
    dependencies: [
        //// Option 1: Fetch latest version available. This allows automatic major version updates that may contain non-backward compatible changes.
        .package(url: "https://github.com/microsoft/clarity-apps", branch: "main")
        //// Option 2: Fetch a specific minor version range (For example, 2.0.0 up to, but not including, 3.0.0).
        // .package(url: "https://github.com/microsoft/clarity-apps", from: "2.0.0")
    ],
    targets: [
        .target(
            name: "<target-name>",
            dependencies: [
                .product(name: "Clarity", package: "clarity-apps")
            ]
        )
    ]
)

Step 2

Note

  • Initialization has to run from the main thread.

Add the following code to AppDelegate.swift file:

import Clarity

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Note: Replace `<project-id>` with actual project ID found Clarity Settings -> Overview page.
        // Note: Set `.verbose` value for `logLevel` parameter while testing to debug initialization issues.
        let clarityConfig = ClarityConfig(projectId: "<project-id>")
        ClaritySDK.initialize(config: clarityConfig)
        return true
    }
    // ...
}

Step 3

Once you integrated Clarity with your application, ensure the following if you want to test it on a device or a simulator:

  1. Your device/simulator is connected to the internet.
  2. Your device/simulator iOS version is within the supported range 15-18 inclusive.
  3. Your first run might require setting the log level to Verbose to obtain the Clarity logs. These logs can help identify any initialization errors, if present.

Allow approximately 2 hours for complete sessions to appear in your Clarity project on the Clarity website. However, in-progress sessions can still be viewed in real time. See Clarity Recordings in Real Time.

Configuration options

class ClarityConfig {
    init(
        projectId: String,
        userId: String? = nil,
        logLevel: LogLevel = .none,
        allowMeteredNetworkUsage: Bool = false,
        enableWebViewCapture: Bool = true,
        disableOnLowEndDevices: Bool = false,
        applicationFramework: ApplicationFramework = .native,
        enableSwiftUI_Experimental: Bool = false
    ) { }
}

Project ID

Distinct project ID from Clarity. You can find it in the Settings page.

User ID

The current user's identifier. The user ID remains persistent across sessions on the same device. If no user ID is specified, a randomly generated one is used.

  • User ID should be a base-36 string and smaller than the upper limit of 1Z141Z4.
  • If an invalid user ID is provided, a randomly generated ID is used, and the invalid user ID is added as the CustomUserID parameter.
  • If an invalid user ID is provided and the user sets the CustomUserID, the invalid user ID is ignored.

Note

CustomUserID has no format restrictions. However, the length should be between 1-255 characters inclusive.

Log Level

The level of logging to show in the device’s Console or XCode’s console while debugging. By default, the SDK logs nothing. Allowed log levels are:

  • .verbose
  • .debug
  • .info
  • .warning
  • .error
  • .none

Allow Metered Network Usage

Allows uploading session data to the servers on device's metered networks. By default, the SDK only uploads sessions on unmetered networks.

Enable WebView Capture

Allows Clarity to capture the web views DOM content for recording and heatmap reconstruction.

Disable on Low-End Devices

When enabled, Clarity doesn't capture any data for the low-end devices.

Enable SwiftUI (Experimental)

When enabled, Clarity should capture SwiftUI views.

Important: SwiftUI support is still experimental and might cause some issues such as unexpected crashes or suboptimal session recordings.

API

initialize()

static func initialize(config: ClarityConfig)

Parameters

config ClarityConfig

Configuration of clarity.

Remarks

  • This function should be called on the main thread only.
  • The initialization function asynchronously executes some of its logic and returns before Clarity is fully initialized.

pause()

static func pause()

Pauses the Clarity capturing logic until a call to the resume function is made.

Remarks

This function should be called on the main thread only.

resume()

static func resume()

Resumes Clarity's capturing logic only if it was previously paused by a call to the pause function.

Remarks

This function should be called on the main thread only.

isPaused()

static func isPaused() -> Bool

Checks if Clarity session data capture is currently paused based on an earlier call to the pause function.

Returns

Bool

true if Clarity is currently in the paused state based on an earlier call to the pause function; otherwise false.

maskView()

static func maskView(_: UIView)

Parameters

_ UIView

The view instance to mask.

Returns

Bool

true if the view was added to the masked views; otherwise false.

Remarks

This function should be called on the main thread only.

unmaskView()

static func unmaskView(_: UIView)

Parameters

_ UIView

The view instance to unmask.

Returns

Bool

true if the view was added to the unmasked views; otherwise false.

Remarks

This function should be called on the main thread only.

setCustomUserId()

static func setCustomUserId(_: String) -> Bool

Parameters

_ String

The custom user ID to associate with this session. This value can't be null or empty, or consists only of whitespace. Maximum length is 255 characters.

Returns

Bool

true if the custom user ID was successfully registered otherwise false.

Remarks

  • This function should be called on the main thread only.
  • The custom user ID value can be used to filter and search sessions on the Clarity dashboard.
  • Unlike the userID, the custom user ID value has fewer restrictions.
  • We recommend not to set any PII values inside this field.

setCustomSessionId()

static func setCustomSessionId(_: String) -> Bool

Parameters

_ String

The custom session ID to associate with this session. This value can't be null or empty, or consists only of whitespace. Maximum length is 255 characters.

Returns

Bool

true if the custom session ID was successfully registered; otherwise false.

Remarks

  • This function should be called on the main thread only.
  • The custom session ID value can be used to filter and search sessions on the Clarity dashboard.

getCurrentSessionId()

static func getCurrentSessionId() -> String?

Returns

String?

A string representing the currently active session ID. If there's no active session, it returns null.

Remarks

  • This function should be called on the main thread only.
  • The retrieved ID can be used to correlate Clarity sessions with other telemetry services you might be using.
  • Initially, this function might return null until the Clarity session begins.

getCurrentSessionUrl()

static func getCurrentSessionUrl() -> String?

Returns

String?

A string representing the URL to play the session recording. If there's no active session, it returns null.

Remarks

Initially, this function might return null until the Clarity session begins.

setCustomTag()

static func setCustomTag(key: String, value: String) -> Bool

Sets a custom tag for the current session.

Parameters

key String

The custom tag key. This value can't be null or empty, or consists only of whitespace.

value String

The custom tag value. This value can't be null or empty, or consists only of whitespace.

Returns

Bool

true if the custom tag was successfully set; otherwise false.

Remarks

This function should be called on the main thread only.

setCurrentScreenName()

static func setCurrentScreenName(name: String?) -> Bool

Sets the name of the currently active screen. Only allowed for React Native apps.

Parameters

name String?

The name of current screen. This value can't be empty, or consists only of whitespace. The value null can be used to unset the screen name.

Returns

Bool

true if the screen name was successfully set/unset; otherwise false.

Remarks

This function should be called on the main thread only.

setOnNewSessionStartedCallback()

func setOnNewSessionStartedCallback(_ callback: @escaping (String) -> Void) -> Bool

Sets a callback that triggers whenever a new session of Clarity starts. The callback should take the session ID as a string.

Parameters

_ (String) -> Void

The callback to be called each time a new session starts.

Returns

Bool

true if the callback was successfully set; otherwise false.

Remarks

  • If this function was called to set a callback after a session already started, the callback triggers immediately with the existing session ID.
  • The callback is guaranteed to run on the main thread.

SwiftUI Modifiers

Important

  • Force masking of input fields is not currently supported. Apply the clarityMask modifier to each input field individually.
  • Clarity might not capture text content when using custom fonts. In such case, use the clarityFontNameHint modifier.

clarityMask()

func clarityMask()

Indicates that Clarity should mask the view's content.

clarityUnmask()

func clarityUnmask()

Indicates that Clarity should unmask the view's content.

clarityFontNameHint()

func clarityFontNameHint(name: String)

Provides a hint to Clarity about the custom font used by the view.

Parameters

name String

The face name of the view's custom font (for example, "HelveticaBold" or customUIFont.fontName).

Implementation Notes

  • The invocation of View masking APIs should occur in the viewDidLoad() of the view controller that hosts the targeted view.

Important

Remember to update your terms & conditions (if any) for your app users after integrating Clarity with your mobile app.

Additionally, since force masking of input fields isn't supported yet, apply masking to each input field instance individually.

FAQ

For more answers, refer to FAQ.

Next steps

IP blocking

Masking

Visit Clarity