Skip to main content
Gainsight Inc.

Install Gainsight PX SDK for iOS

This article explains how developers can use Gainsight PX’s iOS Software Development Kit (SDK) to set it up in their application. 

Overview

The Gainsight PX iOS SDK is a powerful tool that can measure your application’s statistics and provide you with powerful insights about your app. Once the SDK is integrated, users can start creating Events like App Events, Screen Events, Identify Events, and Custom Events. Also, you can view all the users and events coming into your dashboard.

Gainsight PX helps you to measure your users, product, and business. It unlocks insights into your app's funnel, core business metrics, and analyze your product-market fit. 

Installation iOS

Gainsight PX is available through CocoaPods.

https://github.com/Gainsight/px-ios

Warning: Ensure that the framework that you have integrated earlier is removed before proceeding with the installation.

​Click here to view the alternate installation method.

Add Gainsight PX IOS

To add the Gainsight PX framework file in your project:

  1. Navigate to Administration > Products > Mobile tab

Administration Mobile.jpg

  1. Add PXKit.xcframework to your project, which is already downloaded.
  2. [Manual Integration] Navigate to xcode: Choose Target > Embedded Library + PXKit.xcframework.

Notes:

  •  The requirements for the latest release are:
    • xcode 11+

    • Swift 4.2+

  • Engagements are supported only from iOS version 10.3+.

Integration 2.png

Integrate Gainsight PX Editor

Gainsight PX Mobile Editor helps you manage PX engagements and Product Mapper from your mobile application. 

The In-app Editor allows you to:

  • Preview engagements in the mobile app
  • View the Product Tree
  • Create, edit and delete Module/Features 
  • Add Tap Rules for Module/Features

To use the in-app editor, copy the Scheme to integrate your mobile application with the your platforms that Gainsight supports.

copy scheme 2.jpg

You can activate the editor using deep linking and forwarding the link to the SDK. While forwarding the information, you as a developer have the ability to implement your own logic and permissions before launching the editor.

To integrate Gainsight PX with iOS:

  1. Register for editor scheme in Info.plist as per the guidelines mentioned in 

https://developer.apple.com/documentation/xcode/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app

  1. Perform `EnterEditing` in `openURL` method and also in `applicationContinueUserActivity` to support custom URL and deep linking as below:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : 
Any] = [:]) -> Bool {
          GainsightPX.shared.enterEditingMode(url: url)
          return true
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
         guard let incomingURL = userActivity.webpageURL else {
                 return false
         }
         GainsightPX.shared.enterEditingMode(url: incomingURL)
         return true
}                 
          

Using Gainsight PX

This section explains how to get started with Gainsight PX mobile app development. You can customize the default configurations as required. For more information, refer to the Gainsight PX Configuration section of this article. 

Initialize

With this option, Gainsight PX initializes either by using default configurations OR by setting up your product ID in <#APIKey#>. Also, you can modify some of the default configurations, so the Gainsight client works best for you.

import PXKit

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let configurations = AnalyticsConfigurations(apiKey: <#APIKey#>)
GainsightPX.sharedInstance().initialise(configurations: configurations, completionBlock: <#GainsightPXErrorBlock?#> = nil)

return true

Create Events

Events help you to track data from your mobile application. Events are actions associated with your app. Events allow you to track various actions performed by a user on your app. Currently, the Gainsight PX SDK supports four types of events.

App Events

App Events are mostly auto collected by Gainsight PX client, unless disabled. These events include APP_OPENED, APP_INSTALLED, APP_UPDATED, and APP_BACKGROUNDED every instance of an app crash. However, these events are not auto-enabled. You need to configure these events.

Screen Events

  • By using the default configuration, moving from one controller to another automatically creates events for this screen view which has a title (including when coming back to the presenting controller), there are three public method calls:

GainsightPX.sharedInstance().screen(title: <#String#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
GainsightPX.sharedInstance().screen(title: <#String#>, properties: <#[String : Any]?#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
GainsightPX.sharedInstance().screen(screen: <#ScreenEvent#>, properties: [String: Any]?, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
  • The minimum requirement for this call is the screen name. You can also create a screen event with additional properties (For example, parameters that were created to start the page, information that is being displayed, etc.) in the form of Dictionary. The last option is to create a screen event in a more detailed manner: includes screenClass and screenName.

IMPORTANT: In order to log screen views on iOS automatically, PX relies on method swizzling. Apps using SwiftUI must name their views manually.

Identify Events

By identifying the user who is using the app, you can generate more accurate information about their use of the app.

With Only UserId
GainsightPX.sharedInstance().identify(userId: <#String#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
User Object
let user = User(userId: <#UserId#>)
GainsightPX.sharedInstance().identify(user: user, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
Using User and Account
let user = User.init(userId: <#String#>)
let account = Account.init(id: <#String#>)
GainsightPX.sharedInstance().identify(user: <#User#>, account: <#Account?#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)

The minimum requirement for this call is the user id. Each user should be uniquely identified in the system, so they can be identified throughout all devices. You can also identify the user from User and Account objects. While creating one of those objects, you must use user ID (Account ID is not the same as User ID), but you can add more attributes as information on the user. 

There are settings for the common attributes, but it is possible to add custom attributes using:

user.customAttributes = <#[String: Any]#>
account.customAttributes = <#[String: Any]#>

Custom Events

Custom events allow you to track specific events of your choice that you want to see on your dashboard. 

GainsightPX.sharedInstance().custom(event: <#String#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)
GainsightPX.sharedInstance().custom(event: <#String#>, properties: <#[String : Any]?#>, errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)

Adding an event name is mandatory, also you can add event properties to elaborate on the event that happened.

General Method

There are three types of general methods:

Flush

Calling flush directly will send all events in the queue to the server without waiting for the next automatic flush. Usually, you don't need to call it directly, but there are some cases where you might want to make sure that the events are flushed.

GainsightPX.sharedInstance().flush(errorCompletionBlock: <#GainsightPXErrorBlock?#> = nil)

Reset

Resetting the Gainsight PX client is not required but might be useful when a user is signing out from his/her account and we want to associate all of the new events as part of the future user behavior. If reset is not used by a user, they will be registered as part of the logged out user events since the logout action is only in the context of your app and not Gainsight PX framework.

GainsightPX.sharedInstance().reset()
 GainsightPX.shared.hardReset()

 

Enable/Disable

Enabling and disabling the Gainsight PX instance allows you to control events collection. When the instance is disabled, no events are registered to the server (except for SESSION_INITIALIZED). This feature helps you to turn off events that could be auto collected in data-sensitive areas of your app.

Enable 

GainsightPX.shared.engagements(enable: Bool)


Disable

GainsightPX.disable() 

Orientation

If your application handles the interface orientation explicitly using either attemptRotationToDeviceOrientation() API , or UIDevice API, or both, then you need to apply the same orientation to GainsightPX using the following API.

GainsightPX.shared.setSupportedInterfaceOrientations(orientation: UIInterfaceOrientationMask)

For more information on the APIs, refer to the attemptRotationToDeviceOrientation() and UIDevice articles from the Additional Resources section.

The following code snippet depicts the scenario:

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        GainsightPX.shared.setSupportedInterfaceOrientations(orientation: .landscapeRight)
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        GainsightPX.shared.setSupportedInterfaceOrientations(orientation: .portrait)
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    }

Set Global Context 

Once you create all the required events, you can set events with a global context. You can set a global context with key-value pairs and send it with the payload. Global context can be set on Date, String, Double, and Boolean data types. Global Context data is stored at the memory level and not disk-level. The key-value pairs are sent with the Payloads. If an application is terminated, all the key-value pairs are erased. 

Use the following code snippet to set globalContext:

let globalContext = GlobalContext();
globalContext.setDate(key: <#T##String#>, iso: <#T##String#>)
globalContext.setDate(key: <#T##String#>, value: <#T##Date#>)
globalContext.setDouble(key: <#T##String#>, value: <#T##Double#>)
globalContext.setString(key: <#T##String#>, value: <#T##String#>)
globalContext.setBoolean(key: <#T##String#>, value: <#T##Bool#>)
GainsightPX.sharedInstance().globalContext(context: globalContext)

Use the following code to set global context key, and remove the key pair value:

if globalContext.hasKey(key: "foo"){
  globalContext?.removeKeys(keys: ["foo"])
}

EngagementCallBack

Gainsight PX provides the Engagement Callback feature for mobile engagements that you create for mobile applications. This feature helps in receiving a callback for all button actions and URL clicks that the end-user performs on an engagement. Once you receive the callback, you can decide your next action like helping the user to navigate to a new screen, or perform an API call and so on.

Prerequisite

Ensure that you have installed/configured the Gainsight PX Mobile SDK v1.5.1 or above.

To use the Engagement Callback feature for iOS applications, you need to implement the EngagementCallback interface.
iOS PXEngagementCallBack has two variables: EngagementCallBackModel and Error

Add the EngagementCallback functionality as follows:

public typealias PXEngagementCallBack = (EngagementCallBackModel?, Error?) -> Bool
 
GainsightPX.shared.initialise(configurations: configurations,
                                          completionBlock: nil) { callback, error in
   ...
    return true
}

EngagementMetaData Properties

The following table describes the properties in the arguments received from the PXEngagementCallback event listener : 

Property

Type

Description

actionText

string

The text of the linked element.

actionType/
actionsType(iOS Native)

string

Refers to the element that invoked the Engagement Callback.
Possible values: link, button.
 

engagementName

string

Name of the engagement for which the callback is received

scope

object

Mobile screen scope where the engagement is shown.
Possible values: screenName, screenClass.

engagementId

string

ID of the engagement for which the callback is received .

Error Handling

All exceptions occurred when creating events are passed into error callback GainsightPXErrorBlock

public typealias GainsightPXErrorBlock = (<#String#>, <#[String: Any]?#>, <#Error?#>) -> Void

The properties of GainsightPXErrorBlock are as follows:

  • The first parameter informs about the invoked function name.
  • The second parameter gives the event properties that were sent to create an event.
  • The error parameter gives information about the exception that occurred.

Gainsight PX Configurations

This section describes methods, whose configurations can be modified by you during the initialization stage. 

Method Call Default Description Override Server?
flushQueueSize 20 The number of events that are considered to form a batch to be sent to server. Once this limit is reached, PX sends the events to the server even if it's still not the time for that (by the timer) Yes
flushInterval 20 sec The time interval during which the client checks if there are any new events to send to the server Yes
trackApplicationLifecycleEvents true Should be the client auto track app related events (APP_OPENED, APP_INSTALLED and APP_UPDATED) No (Server can drop the event based on remote configuration)

shouldTrackTapEvents

false

Should the client auto-track tap events

Note: Enabling this helps you track only the single tap gestures.

Yes
       
recordScreenViews true Whether or not the client should auto-track screen events No (Server can drop the event based on remote configuration)
crypto GPXCrypto() This protocol will encrypt and decrypt the given  
connection Connection() This will create a connection object which handles requests  
maxQueueSize 1000 The maximum number of items to queue before starting to drop old ones. No

Connection():

Host esp.aptrinsic.com All the data requests are sent to the given host
timeoutIntervalForRequest 15  
timeoutIntervalForResource 20  
  • Was this article helpful?