SDK API reference
The SDK API provides the following methods with their signatures, parameters, and usage examples.
GDPR / Identification
Section titled GDPR / IdentificationCSQ.optIn()
Section titled CSQ.optIn()1.0.0
Get user consent. Calling this API generates a user ID and initiates tracking.
CSQ.optIn()CSQ.optOut()
Section titled CSQ.optOut()1.0.0
Revoke user consent, remove stored userID.
Stop CSQ SDK, flush, and clear all data.
CSQ.optOut()CSQ.identify()
Section titled CSQ.identify()Product Analytics | Added in: 1.0.0
Assigns an identity to be associated with the current user.
This assigns the identity to all events for the user ID and lets the analysis module merge multiple user IDs with the same identity.
This should be called only after Product Analytics is configured and the SDK started. It's safe to call multiple times with the same value. Always provide a value that will be unique to this user. Setting values like "guest", "anonymous", "unauthenticated" or similar will merge all those users into a single user profile.
CSQ.identify("userIdentity")Parameters
Section titled ParametersidentityString (<= 100 chars)Identity to be associated with the current user.
CSQ.resetIdentity()
Section titled CSQ.resetIdentity()1.0.0
If the user was previously identified with identify(), this creates a new unidentified user and session. This is technically similar to calling optOut() then optIn().
This should be called only after Product Analytics is configured and the SDK started.
CSQ.resetIdentity()CSQ.metadata.*****
Section titled CSQ.metadata.*****1.0.0
Get all the information related to the user and project.
CSQ.metadata.userID
Section titled CSQ.metadata.userIDIdentifier of the current user. This is an identifier from Product Analytics by default or Experience Analytics if PA is not active.
let userID = CSQ.metadata.userIDCSQ.metadata.sessionID
Section titled CSQ.metadata.sessionIDSession identifier. This is an identifier from Experience Analytics by default or Product Analytics if Experience Analytics is not active.
let sessionID = CSQ.metadata.sessionIDCSQ.metadata.projectID
Section titled CSQ.metadata.projectIDProject identifier for Experience Analytics.
let projectID = CSQ.metadata.projectIDCSQ.metadata.environmentID
Section titled CSQ.metadata.environmentIDEnvironment identifier for Product Analytics.
let environmentID = CSQ.metadata.environmentIDCSQ.metadata.sessionReplayURL
Section titled CSQ.metadata.sessionReplayURLURL of current Session Replay.
let sessionReplayURL = CSQ.metadata.sessionReplayURLCSQ.metadata.identity
Section titled CSQ.metadata.identityIdentity associated with the user by calling identify().
let identity = CSQ.metadata.identityCSQ.metadata.onChange { metadata in }
Section titled CSQ.metadata.onChange { metadata in }1.0.0
A block triggered each time user information is updated. For example when sessionReplayURL becomes available or userID updates. Set this block to subscribe to the updates. Contentsquare will call this block with updated metadata.
CSQ.metadata.onChange { metadata in // Handle information change}Parameters
Section titled ParametersmetadataMetadataMetadata associated with the current user and project.
Logging
Section titled LoggingCSQ.debug.logLevel
Section titled CSQ.debug.logLevel1.0.0
Gets or sets the current log level.
CSQ.debug.logLevel = .debugParameters
Section titled ParameterslevelEnum (CSQ.Log.Level)Possible values:
none,trace,debug,info,warn,error, orimportant.
CSQ.debug.logChannel
Section titled CSQ.debug.logChannelProduct Analytics | Added in: 1.0.0
Gets or sets the LogChannel to which send log messages.
CSQ.debug.logChannel = customLogChannelParameters
Section titled ParametersLogChannelinterfaceThe interface where log messages will be routed.
LogChannel.printLog()
Section titled LogChannel.printLog()Product Analytics | Added in: 1.0.0
Implement this function to route SDK logs to another location such as CocoaLumberjack, SwiftyBeaver, or similar logging libraries.
The default implementation routes all logs through os_log.
class CustomLogChannel: LogChannel { func printLog(logLevel: Log.Level, message: () -> String, source: String?, file: String, line: UInt) { // your implementation }}Property Tracking
Section titled Property TrackingCSQ.addDynamicVar()
Section titled CSQ.addDynamicVar()Experience Analytics | Added in: 1.0.0
Adds dynamic variables to the session properties.
This method allows you to pass DynamicVar object, representing a key-value pair that is scoped to the session.
let var1 = DynamicVar(key: "key1", value: "value1")let var2 = DynamicVar(key: "key2", value: 2)
CSQ.addDynamicVar(var1)CSQ.addDynamicVar(var2)Parameters
Section titled ParametersdVarDynamicVarThe dynamic variable
keyString (<= 512 chars)Dynamic variable key
intValueUInt32Dynamic variable integer value
stringValueStringDynamic variable string value
CSQ.addUserProperties()
Section titled CSQ.addUserProperties()Product Analytics | Added in: 1.0.0
Add a collection of properties to be associated with the current user.
CSQ.addUserProperties(["propertyKey"": "propertyValue"])Parameters
Section titled Parametersproperties[String: PropertyValue]A dictionary of user properties.
PropertyValuecan beString,Substring,Bool,Double,Float,Int,Int64,Int32,Int16orInt8.
CSQ.addEventProperties()
Section titled CSQ.addEventProperties()Product Analytics | Added in: 1.0.0
Add a collection of properties to be associated with all future events.
CSQ.addEventProperties(["propertyKey": "propertyValue"])Parameters
Section titled Parametersproperties[String: PropertyValue]A dictionary of event properties.
PropertyValuecan beString,Substring,Bool,Double,Float,Int,Int64,Int32,Int16orInt8.
CSQ.removeEventProperty()
Section titled CSQ.removeEventProperty()Product Analytics | Added in: 1.0.0
Removes a single property from the collection of event-wide properties.
CSQ.removeEventProperty("propertyKey")Parameters
Section titled ParameterskeyStringThe key of the property to remove.
CSQ.clearEventProperties()
Section titled CSQ.clearEventProperties()Product Analytics | Added in: 1.0.0
Removes all event-wide properties.
CSQ.clearEventProperties()View Tracking
Section titled View TrackingUIViewController.csqScreenNameOverride
Section titled UIViewController.csqScreenNameOverrideProduct Analytics | Added in: 1.13.0
Overriding this property replaces the autocaptured screen name for the given class.
extension SignUpFlowViewController { open override class var csqScreenNameOverride: String? { "Main Signup Flow" }}For more details check our Product Analytics documentation.
View.csqScreenName()
Section titled View.csqScreenName()Product Analytics | Added in: 1.2.0
Provide the screen name for a SwiftUI screenview.
TransactionView().csqScreenName("TransactionScreen")Parameters
Section titled ParametersscreenNameStringThe screen name to use when the view appears on screen.
For more details check our Product Analytics documentation.
UIScrollView.excludeFromExposureMetrics()
Section titled UIScrollView.excludeFromExposureMetrics()Experience Analytics | Added in: 1.0.0
Exclude a scrollable view or subclass from Exposure Metric computations.
let scrollView = UIScrollView()scrollView.excludeFromExposureMetrics()CSInApp
Section titled CSInAppCSQ.handle()
Section titled CSQ.handle()Experience Analytics | Added in: 1.0.0
Allows the Contentsquare SDK to monitor CS in-app features activation through a custom URL scheme.
For more details check our CSInApp documentation.
CSQ.handle(url: <CSInAppURL>))Parameters
Section titled ParametersCSQ.csInApp
Section titled CSQ.csInAppExperience Analytics | Added in: 1.0.0
Boolean to manually activate or deactivate in-app features.
When CSQ.csInApp = true, the in-app function is activated automatically at app start.
CSQ.csInApp = trueInteroperability
Section titled InteroperabilityCSQ.registerWebView()
Section titled CSQ.registerWebView()Experience Analytics | Added in: 1.0.0
Register a webview for tracking.
let webView = WKWebView()CSQ.registerWebView(webView)Parameters
Section titled ParameterswebViewWKWebViewThe webview to register for tracking.
CSQ.unregisterWebView()
Section titled CSQ.unregisterWebView()1.0.0
Unregister a webview for tracking.
CSQ.unregisterWebView(webView)Parameters
Section titled ParameterswebViewWKWebViewThe webview to unregister from tracking.
Event Tracking
Section titled Event TrackingCSQ.trackTransaction()
Section titled CSQ.trackTransaction()Experience Analytics | Added in: 1.0.0
Send a transaction.
let transaction = Transaction(id: "transactionId", total: 100.0, currency: .usd)CSQ.trackTransaction(transaction)Parameters
Section titled ParametersTransactionTransactionThe transaction object to be sent. Initialized with id, total, and ISO 4217 currency enum.
CSQ.trackScreenview()
Section titled CSQ.trackScreenview()1.0.0
Send a screen view with or without custom variables. Requires Experience Analytics to be started.
CSQ.trackScreenview(name: "ScreenName", cvars: [CustomVar(index: 1, name: "name", value: "value")])Parameters
Section titled ParametersnameStringThe name of the screen.
cvarsCustomVar[] (optional)An array of custom variables to attach to the screen view.
indexUInt32Custom variable index
keyString (<= 512 chars)Custom variable key
valueString (<= 256 chars)Custom variable value
CSQ.trackEvent()
Section titled CSQ.trackEvent()Product Analytics | Added in: 1.0.0
Creates an event message to be tracked and sent to the API.
CSQ.trackEvent(name: String, properties: ["propertyKey": "propertyValue"]?)Parameters
Section titled ParametersnameStringThe name of the event to be tracked.
properties[String: PropertyValue>] (optional)Optional properties to associate with the event.
PropertyValuecan beString,Substring,Bool,Double,Float,Int,Int64,Int32,Int16orInt8.
Surveys
Section titled SurveysCSQ.triggerSurvey()
Section titled CSQ.triggerSurvey()Experience Analytics Voice of Customer | Added in: 1.0.0
Triggers a survey by referencing a predefined trigger name.
This method allows your mobile app to trigger surveys at specific moments in the user journey. Triggers act as flexible placeholders that are not bound to individual surveys, enabling your business team to assign or update surveys later without requiring code changes.
CSQ.triggerSurvey(triggerName)Parameters
Section titled ParameterstriggerNameStringThe name of the trigger associated with the survey. This should match the trigger name configured in the Contentsquare platform.
Example
Section titled Example// Trigger a survey after a purchase is completedCSQ.triggerSurvey("purchase-complete")Error tracking
Section titled Error trackingCSQ.setUrlMaskingPatterns()
Section titled CSQ.setUrlMaskingPatterns()Experience Analytics | Added in: 1.0.0
Sets URL masking patterns.
CSQ.setUrlMaskingPatterns(["pattern1", "pattern2"])Parameters
Section titled Parameterspatterns[String]A list of URL patterns to mask.
CSQ.onCrashReporterStart()
Section titled CSQ.onCrashReporterStart()Experience Analytics | Added in: 1.0.0
Trigger a callback when the Contentsquare Crash Reporter is initialized.
CSQ.onCrashReporterStart { enabled in // do your work here, e.g. start Firebase Crashlytics}Parameters
Section titled ParametersonCrashReporterStart(enabled: Bool -> Void)Closure triggered when crash reporter is started. Passes a boolean indicating if crash reporter is actually enabled.
CSQ.sendUserIdentifier()
Section titled CSQ.sendUserIdentifier()Experience Analytics | Added in: 1.0.0
Associate the user identifier to the session.
CSQ.sendUserIdentifier("any_identifier")Parameters
Section titled ParametersuserIdentifierStringThe user identifier to track. Should be max 100 characters long.
CSQ.trackNetworkMetric()
Section titled CSQ.trackNetworkMetric()Experience Analytics | Added in: 1.0.0
Track network metrics.
let networkMetric = NetworkMetric(url: "https://example.com", httpMethod: "GET")CSQ.trackNetworkMetric(networkMetric)Parameters
Section titled ParametersnetworkMetricNetworkMetricNetworkMetric object for a network request to collect HTTP network errors.
Personal Data/Masking
Section titled Personal Data/MaskingCSQ.ignoreInteractions()
Section titled CSQ.ignoreInteractions()1.0.0
Ignore interactions for a specific view.
CSQ.ignoreInteractions(view)Parameters
Section titled ParametersUIView.csqIgnoreInteractions
Section titled UIView.csqIgnoreInteractionsUIKit IBInspectable | Added in: 1.0.0
Ignore interactions for a specific view.
view.csqIgnoreInteractions = trueView.csqIgnoreInteractions()
Section titled View.csqIgnoreInteractions()Product Analytics SwiftUI | Added in: 1.2.0
Ignore interactions for a specific view.
Text("Hello World!").csqIgnoreInteractions(shouldIgnore: true)Parameters
Section titled ParametersshouldIgnoreBoolWhether to ignore interactions.
CSQ.setDefaultMasking()
Section titled CSQ.setDefaultMasking()Experience Analytics | Added in: 1.0.0
Set the default masking state. All UIView elements, their subclasses and SwiftUI components are fully masked by default.
CSQ.setDefaultMasking(true)Parameters
Section titled ParametersmaskedBoolThe default masking state to be set.
CSQ.mask(UIView)
Section titled CSQ.mask(UIView)1.0.0
Mask a view's content.
CSQ.mask(view)Parameters
Section titled ParametersviewUIViewThe view which content will be masked.
CSQ.unmask(UIView)
Section titled CSQ.unmask(UIView)1.0.0
Unmask a view's content.
CSQ.unmask(view)Parameters
Section titled ParametersviewUIViewThe view which content will be unmasked.
UIView.csqMaskContents
Section titled UIView.csqMaskContentsUIKit IBInspectable | Added in: 1.0.0
Mask the content of a view.
view.csqMaskContents = trueView.csqMaskContents
Section titled View.csqMaskContentsSwiftUI | Added in: 1.0.0
Mask the content of a view.
Text("Hello World!").csqMaskContents(true)Parameters
Section titled ParametersenableBoolWhether to mask the content of the view.
CSQ.mask(viewsOfType: UIView.Type)
Section titled CSQ.mask(viewsOfType: UIView.Type)Experience Analytics | Added in: 1.0.0
Mask content for views of a specific type.
CSQ.mask(viewsOfType: UIView.Type)Parameters
Section titled ParametersviewsOfTypeUIView.TypeThe class type of the view whose content will be masked.
CSQ.unmask(viewsOfType: UIView.Type)
Section titled CSQ.unmask(viewsOfType: UIView.Type)1.0.0
Unmask content for views of a specific type.
CSQ.unmask(viewsOfType: UIView.self)Parameters
Section titled ParametersviewsOfTypeUIView.TypeThe class type of the view whose content will be unmasked.
CSQ.maskTexts()
Section titled CSQ.maskTexts()1.0.0
Mask all texts.
CSQ.maskTexts(true)Parameters
Section titled ParametersmaskBoolWhether to mask text.
CSQ.maskImages()
Section titled CSQ.maskImages()Experience Analytics | Added in: 1.0.0
Mask images.
CSQ.maskImages(true)Parameters
Section titled ParametersmaskBoolWhether to mask images.
CSQ.maskTextInputs()
Section titled CSQ.maskTextInputs()Experience Analytics | Added in: 1.0.0
Mask text input fields.
CSQ.maskTextInputs(true)Parameters
Section titled ParametersmaskBoolWhether to mask text inputs.
CSQ.encrypt()
Section titled CSQ.encrypt()Mark a view's content to be collected encrypted in Session Replay, instead of being masked. Encryption only applies to views that display text; applying it to a container view has no effect on the views inside it. Call it before you add the view to the view hierarchy.
CSQ.encrypt(view: view)Parameters
Section titled ParametersviewUIViewThe view whose content will be collected encrypted.
View.csqEncrypt()
Section titled View.csqEncrypt()Mark a view's content to be collected encrypted in Session Replay, instead of being masked. Encryption only applies to views that display text; applying it to a container view has no effect on the views inside it.
Text("Hello World!").csqEncrypt()CSQ.clearEncrypt()
Section titled CSQ.clearEncrypt()Remove the encryption mark previously set with CSQ.encrypt(). Call it for reusable views, such as table or collection view cells, so the encryption state doesn't carry over to new content.
CSQ.clearEncrypt(view: view)Parameters
Section titled ParametersviewUIViewThe view to stop encrypting.
UIView.csqIgnoreInnerHierarchy
Section titled UIView.csqIgnoreInnerHierarchyProduct Analytics UIKit IBInspectable | Added in: 1.0.0
If set on a view or view controller, all touches inside that control will be attributed to it rather than child views. This can be helpful in blocking sensitive parts of an interaction and keeping implementation details out of a view hierarchy. For example, Contentsquare uses this property internally to suppress inner touches on UIDatePicker.
let view = UIView()view.csqIgnoreInnerHierarchy = trueSDK Initialization and Management
Section titled SDK Initialization and ManagementCSQ.configureProductAnalytics()
Section titled CSQ.configureProductAnalytics()Deprecated Product Analytics | Added in: 1.0.0
SDK configuration method for Product Analytics. Use CSQ.start() instead, which combines configuration and initialization in a single call.
CSQ.start()
Section titled CSQ.start()1.0.0
Start the SDK. This method combines configuration and initialization in a single call.
There are three overloads depending on whether you want Experience Analytics, Product Analytics, or CSQ Experience Platform.
Experience Analytics only:
CSQ.start()Product Analytics (optionally with Experience Analytics extension) with environmentID:
CSQ.start( environmentID: "YOUR_ENVIRONMENT_ID", options: [ .enableNativeAutocapture: true ])CSQ Experience Platform with dataSourceID:
CSQ.start( dataSourceID: "YOUR_DATASOURCE_ID", options: [ .enableNativeAutocapture: true ])Parameters
Section titled ParametersenvironmentIDString (optional)Your Product Analytics environment ID.
dataSourceIDString (optional)Your CSQ Experience Platform data source ID. Enables both Product Analytics and Experience Analytics with a single identifier.
options[AnalyticsOption: Any] (optional)
CSQ.stop()
Section titled CSQ.stop()1.0.0
Stop all activity from the SDK. Once run no requests, telemetry collection, or logs will be generated.
CSQ.stop()CSQ.pauseTracking()
Section titled CSQ.pauseTracking()1.0.0
Pause all tracking features.
CSQ.pauseTracking()CSQ.resumeTracking()
Section titled CSQ.resumeTracking()1.0.0
Resume all tracking features.
CSQ.resumeTracking()Known limitation: screenviews while tracking is paused
Section titled Known limitation: screenviews while tracking is pausedThe SDK doesn't send a screenview that you track while tracking is paused. If you navigate to a new screen while tracking is paused and then call CSQ.resumeTracking(), the new screen has no screenview unless you send it yourself. For example, this happens when you pause tracking on a sensitive screen and resume it on the next one.
To avoid this, follow this sequence on the screen displayed after the pause:
- Send the screenview of the screen with
CSQ.trackScreenview(). - Call
CSQ.resumeTracking()when the screen is about to be visible, for example inviewWillAppear(UIKit) oronAppear(SwiftUI), right after sending the screenview.
The following example pauses tracking on a sensitive screen and resumes it on the next screen:
// Sensitive screenoverride func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) CSQ.stop()}
// Screen displayed after the sensitive screenoverride func viewDidLoad() { super.viewDidLoad() CSQ.trackScreenview("tracked screen") // 1. Send the screenview first}
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) CSQ.resumeTracking() // 2. Then resume tracking}// Sensitive screenstruct SensitiveView: View { var body: some View { // ... .onAppear { CSQ.stop() } }}
// Screen displayed after the sensitive screenstruct NextView: View { var body: some View { // ... .onAppear { CSQ.trackScreenview("Tracked screen") // 1. Send the screenview first CSQ.resumeTracking() // 2. Then resume tracking } }}CSQ.startSessionReplay()
Section titled CSQ.startSessionReplay()1.10.0
Enable and eventually start Session Replay independently of other CSQ SDK features, allowing for on-demand collection.
To use this functionality, disable the automatic start of Session Replay at SDK initialization using the .sessionReplayAutoStart option.
CSQ.startSessionReplay()CSQ.stopSessionReplay()
Section titled CSQ.stopSessionReplay()1.10.0
Stop Session Replay immediately.
CSQ.stopSessionReplay()SDK configuration options
Section titled SDK configuration optionsCSQ SDK options passed to CSQ.start().
CSQ.start( options: [ ])uploadInterval
Section titled uploadIntervalThe interval in seconds between event batch uploads. Accepts a TimeInterval (Double) value.
baseURL
Section titled baseURLThe CSQ API endpoint to use:
https://mh.ba.contentsquare.net— EU-hosted environmentshttps://mh.bf.contentsquare.net— all other environments (default)
disablePageviewAutocapture
Section titled disablePageviewAutocaptureWhether source pageview events will be auto-captured.
Defaults to false.
disablePageviewTitleAutocapture
Section titled disablePageviewTitleAutocaptureWhether autocapture of pageview titles is disabled. Defaults to false.
disableInteractionAutocapture
Section titled disableInteractionAutocaptureDisables autocapture of touch events on UIKit views. Defaults to false.
enableNativeAutocapture
Section titled enableNativeAutocaptureWhether to enable autocapture of native UIKit view interaction events. Defaults to false.
enablePushNotificationAutocapture
Section titled enablePushNotificationAutocaptureWhether the SDK will auto capture interaction events on notifications.
Defaults to false.
enablePushNotificationTitleAutocapture
Section titled enablePushNotificationTitleAutocaptureWhether to capture the title of the notification where an interaction was performed. enablePushNotificationAutocapture must be set to true.
Defaults to false.
enablePushNotificationBodyAutocapture
Section titled enablePushNotificationBodyAutocaptureWhether to capture the body text of the notification where an interaction was performed. enablePushNotificationAutocapture must be set to true.
Defaults to false.
sessionReplayAutoStart
Section titled sessionReplayAutoStartWhether Session Replay starts automatically at SDK launch. Defaults to true.
Set to false to disable automatic start and control Session Replay manually.

