---
sourceDocument: Xanadu API Reference
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/xanadu/api-reference

 Release :

    - xanadu

ft:locale :

    - en-US

ft:publication_title :

    - Xanadu API Reference

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# NowAnalyticsService protocol - iOS

# NowAnalyticsService protocol - iOS {#ariaid-title1}

* Release version: Xanadu
* 
* Updated August 1, 2024
* 
* ![](https://www.servicenow.com/docs/portal-asset/ico-clock) 6 minutes to read

The NowAnalyticsService protocol provides functions that enable you
to configure analytics properties, user settings, and events for managing the collection of user
analytics data.

An object conforming to this protocol is returned by `sharedAnalyticsService`.
Use it in your application to perform API calls.  
{#NowAnalyticsServiceiOSProtocol__table_vx2_klw_5pb__entry__3}

| Name | Type | Description |
|-|-|-|
| trackingConsent | Boolean | Flag that indicates whether the user has consented to analytics tracking for the associated device. By default, devices are opted-out. Explicitly setting this value to `false` will immediately finish any ongoing session and delete the locally recorded data. Valid values: * true: User consented to anlaytics data being tracked on this device. * false: User denied data tracking. {#NowAnalyticsServiceiOSProtocol__ul_flc_ngx_5pb} |
[Table 1. Requirements]

{#NowAnalyticsServiceiOSProtocol__table_vx2_klw_5pb}

## NowAnalyticsService - addEvent(named eventName: String, with properties: \[String:
Any\]?) {#ariaid-title2}

Adds an application event, such as a user reaching a specific level or screen, and
enables the setting of custom properties on the event. These events appear on the dashboard in
the order that they occurred.
These events appear in your analytics dashboard.
{#NAnalyServiOs-addEvent_S_A__table_hwl_5vy_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| named eventName | String | Name of the event to add. |
| with properties | Array | Optional. Custom property key-value pairs for the event. Property keys may not contain the dot ('.') or dollar ('$') signs. They will be trimmed. Supported value types: * Date * NSNull * NSNumber * Strings * URL {#NAnalyServiOs-addEvent_S_A__ul_g41_kxy_spb} Note: The total size of the eventName, properties key and value should not exceed 300 bytes (per event). Strings are UTF-8 encoded. Events that exceed this limit are ignored. |
[Table 2. Parameters]

{#NAnalyServiOs-addEvent_S_A__table_hwl_5vy_spb} {#NAnalyServiOs-addEvent_S_A__table_iwl_5vy_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 3. Returns]

{#NAnalyServiOs-addEvent_S_A__table_iwl_5vy_spb}  
The following example shows how to add a "Successful Login" event and an "Open Case" event
with properties.

    // Add event with properties
    NowAnalytics.sharedAnalyticsService.addEvent(
      named: "Open Case", with: ["Screen Name": "Case",
                                 "Case Number": "123",
                                 "Case Priority": 5
    ])

## NowAnalyticsService - addScreenAction(named actionName: String) {#ariaid-title3}

Adds a custom action to the current screen. These actions appear in the user dashboard
as part of the session data and describes a screen change in an application.
{#NAnalyServiOS-addScreenAction_S__table_lxc_hzy_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| named actionName | String | Name of the action to add to the screen, such as <kbd class="ph userinput">MyButtonClick</kbd>. Maximum length: 256 UTF-8 bytes |
[Table 4. Parameters]

{#NAnalyServiOS-addScreenAction_S__table_lxc_hzy_spb} {#NAnalyServiOS-addScreenAction_S__table_mxc_hzy_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 5. Returns]

{#NAnalyServiOS-addScreenAction_S__table_mxc_hzy_spb}  
<br />

    // Add event
    NowAnalytics.sharedAnalyticsService.addEvent(named: "Successful Login")

## NowAnalyticsService - appendToUserProperty(named propertyName: String, listItem:
String) {#ariaid-title4}

Appends
the specified item to the specified user property list.
{#NAnalyServiOS-appendToUserProp_S_S__table_uhf_jd1_tpb__entry__3}

| Name | Type | Description |
|-|-|-|
| named propertyName | String | Name of the user property list to append the listItem to. |
| listItem | String | List item to append to the property. |
[Table 6. Parameters]

{#NAnalyServiOS-appendToUserProp_S_S__table_uhf_jd1_tpb} {#NAnalyServiOS-appendToUserProp_S_S__table_vhf_jd1_tpb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 7. Returns]

{#NAnalyServiOS-appendToUserProp_S_S__table_vhf_jd1_tpb}  
<br />

    // Append handled case to list
    NowAnalytics.sharedAnalyticsService.appendToUserProperty(named: "Case Identifiers", listItem: "TASK-1")

## NowAnalyticsService - deleteCurrentUserData(completion: @escaping ((_ success: Bool) -\>
Void)) {#ariaid-title5}

Deletes all analytics data associated with the current user. This method also unsets
the current active user and opts this device out of future tracking.
To set the current user, use the [setUserId()](https://servicenow-prod.fluidtopics.net/BbHYbABSv6yhida7B73Hgw#NAnalyServiOS-setUserId_S "Sets the application's user ID for the current user. Pass nil to log out the current user.") method.
{#NAnalyServiOS-deleteCurrentUserData_O__table_akt_yry_spb__entry__3}{#NAnalyServiOS-deleteCurrentUserData_O__mobilesdkiOS-completion_data_dataerror-row}

| Name | Type | Description |
|-|-|-|
| completion | @escaping ((_ success: Bool) -\> Void) | Completion handler to execute after the analytics data is deleted. Return values for the completion handler: * Success: Returns a Boolean value of true. * Failure: Void - Failure may occur if the Appsee servers cannot be reached, as when there is no connectivity. If failure occurs, retry the method. {#NAnalyServiOS-deleteCurrentUserData_O__ul_uzx_thj_ppb} |
[Table 8. Parameters]

{#NAnalyServiOS-deleteCurrentUserData_O__table_akt_yry_spb} {#NAnalyServiOS-deleteCurrentUserData_O__table_bkt_yry_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 9. Returns]

{#NAnalyServiOS-deleteCurrentUserData_O__table_bkt_yry_spb}  
<br />

    // Delete user data
    NowAnalytics.sharedAnalyticsService.deleteCurrentUserData(completion: { (success) -> Void in
      if success {
        // deletion succeeded
      } else {
        // deletion failed
      }
    })

## NowAnalyticsService - incUserProperty(named propertyName: String, by value: Int) {#ariaid-title6}

Increments or decrements the value of the specified numeric property by the specified
value.
{#NAnalyServiOS-incUserProperty_S_I__table_fkc_chz_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| named propertyName | String | Name of the user property to increment. |
| by value | Integer | Value to increment the property by. Enter a negative value to decrement the value. |
[Table 10. Parameters]

{#NAnalyServiOS-incUserProperty_S_I__table_fkc_chz_spb} {#NAnalyServiOS-incUserProperty_S_I__table_gkc_chz_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 11. Returns]

{#NAnalyServiOS-incUserProperty_S_I__table_gkc_chz_spb}  
<br />

    // Increment the "Cases Handled" count
    NowAnalytics.sharedAnalyticsService.incUserProperty(named: "Cases Handled", by: 2)

## NowAnalyticsService - installJavascriptInterface(into webView: WKWebView) {#ariaid-title7}

Enables the calling of the methods in the SNAnalytics() API from
within a WebView using JavaScript.
This method returns an [SNMobileAnalytics](https://servicenow-prod.fluidtopics.net/y3wFtKI9hmxTbRucblauEQ#SNMobileAnalytics "The SNMobileAnalytics API provides methods that you can call within a WebView using JavaScript. These methods enable you to push custom analytics data (events, pages, and user properties) to the User Experience Analytics for Service Portal dashboard.") object that is available in JavaScript, which exposes the native methods.
{#NAnalyServiOS-installJSInterface_O__table_pqj_dh1_tpb__entry__3}

| Name | Type | Description |
|-|-|-|
| webView | WKWebView | Web view object in which to inject the JavaScript interface. |
[Table 12. Parameters]

{#NAnalyServiOS-installJSInterface_O__table_pqj_dh1_tpb} {#NAnalyServiOS-installJSInterface_O__table_qqj_dh1_tpb__entry__2}

| Type | Description |
|-|-|
| Object | [SNMobileAnalytics](https://servicenow-prod.fluidtopics.net/y3wFtKI9hmxTbRucblauEQ#SNMobileAnalytics "The SNMobileAnalytics API provides methods that you can call within a WebView using JavaScript. These methods enable you to push custom analytics data (events, pages, and user properties) to the User Experience Analytics for Service Portal dashboard.") |
[Table 13. Returns]

{#NAnalyServiOS-installJSInterface_O__table_qqj_dh1_tpb}  
<br />

    // Register JS object inside the web page
    // This will create an object named 'SNMobileAnalytics' on JS that will have the following methods:
    // SNMobileAnalytics.setUserId(userId)                  example: SNMobileAnalytics.setUserId("John Doe")
    // SNMobileAnalytics.startScreen(screenName)            example: SNMobileAnalytics.startScreen("WelcomeScreen")
    // SNMobileAnalytics.addScreenAction(actionName)        example: SNMobileAnalytics.addScreenAction("MyButtonClick")
    // SNMobileAnalytics.addEvent(eventName, properties)    example: SNMobileAnalytics.addEvent("Successful Login")
    //                                                               SNMobileAnalytics.addEvent("Successful Login", JSON.stringify({"Screen Name": "Case", "Case Number": "123", "Case Priority": 5}))
    NowAnalytics.sharedAnalyticsService.installJavascriptInterface(into: webView)

## NowAnalyticsService - removeUserProperty(named propertyName: String) {#ariaid-title8}

Deletes the specified property for the current user.
To set the current user, use the [setUserId()](https://servicenow-prod.fluidtopics.net/BbHYbABSv6yhida7B73Hgw#NAnalyServiOS-setUserId_S "Sets the application's user ID for the current user. Pass nil to log out the current user.") method.
{#NAnalyServiOS-removeUserProp_S__table_jdm_lf1_tpb__entry__3}

| Name | Type | Description |
|-|-|-|
| named propertyName | String | Name of the user property to delete. |
[Table 14. Parameters]

{#NAnalyServiOS-removeUserProp_S__table_jdm_lf1_tpb} {#NAnalyServiOS-removeUserProp_S__table_kdm_lf1_tpb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 15. Returns]

{#NAnalyServiOS-removeUserProp_S__table_kdm_lf1_tpb}  
<br />

    // Remove unnecessary property
    NowAnalytics.sharedAnalyticsService.removeUserProperty(named: "Temp Cases")

## NowAnalyticsService - setDelegate(_ delegate: NowAnalyticsServiceDelegate?) {#ariaid-title9}

Sets a weak reference for a delegate to receive notifications.
{#NAnalyServiOS-setDelegate_O__table_d42_j31_tpb__entry__3}

| Name | Type | Description |
|-|-|-|
| delegate | [NowAnalyticsServiceDelegate](https://servicenow-prod.fluidtopics.net/NODKHm0VZfW_LI0npGr6Pw#NowAnalyticsServiceDeliOSProtocol "The NowAnalyticsServiceDelegate protocol provides callback functions that provide information about the starting and ending of a user session and screen change detection.") | Optional. Object that contains the reference to the delegate class. // Register delegate private var analyticsDelegate = NowAnalyticsDelegate()  // Keep ref of delegate NowAnalytics.sharedAnalyticsService.setDelegate(analyticsDelegate) |
[Table 16. Parameters]

{#NAnalyServiOS-setDelegate_O__table_d42_j31_tpb} {#NAnalyServiOS-setDelegate_O__table_e42_j31_tpb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 17. Returns]

{#NAnalyServiOS-setDelegate_O__table_e42_j31_tpb}  
This example shows how to define a delegate class for
NowAnalyticsServiceDelegate.

    // Define a delegate class for NowAnalyticsServiceDelegate
    class NowAnalyticsDelegate: NowAnalytics.NowAnalyticsServiceDelegate {
      func nowAnalyticsSessionShouldStart() -> Bool {
        // Session is about to start, return true to allow session to start
        return true
      }

      func nowAnalyticsSessionDidStart(_ sessionId: String) {
        // Session was started
      }

      func nowAnalyticsSessionShouldEnd(_ sessionId: String) -> Bool {
        // Session is about to end, return true to allow session to end
        return true
      }

      func nowAnalyticsSessionDidEnd(_ sessionId: String) {
        // Session was ended
      }

      func nowAnalyticsDidDetectScreen(_ screenName: String) -> String? {
        // Example of skipping specific screen detection
        if (screenName == "LoginViewController") {
          return nil
        }

        // Example of appending a prefix for every screen detected
        return "MyApp_" + screenName
      }
    }

    // Register delegate
    private var analyticsDelegate = NowAnalyticsDelegate()  // Keep ref of delegate
    NowAnalytics.sharedAnalyticsService.setDelegate(analyticsDelegate)

## NowAnalyticsService - setUserId(_ userId: String?) {#ariaid-title10}

Sets the application's user ID for the current user. Pass nil to log out the current
user.
{#NAnalyServiOS-setUserId_S__table_r2r_x1z_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| userId | String | Optional. Application-specific user identifier. To log the current user out, pass `nil`. The user ID must not contain HTML tags or any personal data such as name, email, or phone number. Maximum length: 256 UTF-8 bytes |
[Table 18. Parameters]

{#NAnalyServiOS-setUserId_S__table_r2r_x1z_spb} {#NAnalyServiOS-setUserId_S__table_s2r_x1z_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 19. Returns]

{#NAnalyServiOS-setUserId_S__table_s2r_x1z_spb}  
<br />

    // Add several properties at once
    NowAnalytics.sharedAnalyticsService.setUserProperties([
      "Cases Handled": 100,
      "Last Login": Date(),
      "Is Remote": true,
      "Profile URL": URL(string: "https://www.servicenow.com")!
    ])

## NowAnalyticsService - setUserProperties(_ userProperties: \[String: Any\]) {#ariaid-title11}

Sets multiple properties with the specified values for the current user. Properties can
be anything that you want to track on the dashboard for a user.
You must call the [setUserId()](https://servicenow-prod.fluidtopics.net/BbHYbABSv6yhida7B73Hgw#NAnalyServiOS-setUserId_S "Sets the application's user ID for the current user. Pass nil to log out the current user.") function
before calling this function.
{#NAnalyServiOS-setUserProperties_A__table_o5w_vfz_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| userProperties | Array | Key-value pairs of the user properties to set. Supported value types: * NSNumber * Strings * Date * URL * NSNull Key may not contain dots ('.') or dollar ('$') signs. Maximum length: * key: 256 characters * value: 1,000 characters {#NAnalyServiOS-setUserProperties_A__ul_vqr_1rc_zpb} |
[Table 20. Parameters]

{#NAnalyServiOS-setUserProperties_A__table_o5w_vfz_spb} {#NAnalyServiOS-setUserProperties_A__table_p5w_vfz_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 21. Returns]

{#NAnalyServiOS-setUserProperties_A__table_p5w_vfz_spb}  
<br />

    import NowAnalytics

    // Initialize the Analytics SDK
    NowAnalytics.configure(for: URL(string: "https://my.instance.service-now.com")!)

    // Enable tracking consent
    NowAnalytics.sharedAnalyticsService.trackingConsent = true

    // Set User Id for proper identification
    NowAnalytics.sharedAnalyticsService.setUserId("John Doe")

    // Set the "Role" property of the user to "Admin"
    NowAnalytics.sharedAnalyticsService.setUserProperty(named: "Role", with: "Admin")

    // Add several properties at once
    NowAnalytics.sharedAnalyticsService.setUserProperties([
        "Cases Handled": 100,
        "Last Login": Date(),
        "Is Remote": true,
        "Profile URL": URL(string: "https://www.servicenow.com")!
    ])

## NowAnalyticsService - setUserProperty(named propertyName: String, with value: Any?) {#ariaid-title12}

Sets the specified property with the specified value for the current user. You can
define any property that makes sense for your application.
You must call the [setUserId()](https://servicenow-prod.fluidtopics.net/BbHYbABSv6yhida7B73Hgw#NAnalyServiOS-setUserId_S "Sets the application's user ID for the current user. Pass nil to log out the current user.") function
before calling this function.
{#NAnalyServiOS-setUserProperty_S_A__table_idn_sdz_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| named propertyName | String | Name of the user property to set. May not contain dots ('.') or dollar ('$') signs. Maximum length: 256 characters |
| with value | Any | Value to set the user property to. Supported value types: * Date * NSNull * NSNumber * Strings * URL Maximum length: 1,000 characters |
[Table 22. Parameters]

{#NAnalyServiOS-setUserProperty_S_A__table_idn_sdz_spb} {#NAnalyServiOS-setUserProperty_S_A__table_jdn_sdz_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 23. Returns]

{#NAnalyServiOS-setUserProperty_S_A__table_jdn_sdz_spb}  
<br />

    // Set the "Role" property of the user to "Admin"
    NowAnalytics.sharedAnalyticsService.setUserProperty(named: "Role", with: "Admin")

## NowAnalyticsService - startScreen(named screenName: String) {#ariaid-title13}

Logs the time when the associated screen first appears in the UI.
Call this method after the viewDidAppear(_:) method.
{#NAnalyServiOS-startScreen_S__table_vw5_fyy_spb__entry__3}

| Name | Type | Description |
|-|-|-|
| named screenName | String | Name of the screen to log the start time for, such as <kbd class="ph userinput">WelcomeScreen </kbd>. This can be anything that you want to define as a screen and display/aggregate on an analytics dashboard. Maximum length: 256 UTF-8 bytes |
[Table 24. Parameters]

{#NAnalyServiOS-startScreen_S__table_vw5_fyy_spb} {#NAnalyServiOS-startScreen_S__table_ww5_fyy_spb__entry__2}

| Type | Description |
|-|-|
| None |   |
[Table 25. Returns]

{#NAnalyServiOS-startScreen_S__table_ww5_fyy_spb}  
<br />

    // Mark the appearance starting time of a screen
    // This method should be usually called from the viewDidAppear
    NowAnalytics.sharedAnalyticsService.startScreen(named: "WelcomeScreen")


