iOS - v9.0.0-beta

Updated 

Step A - To start with this, download the messenger zip and podspec file and keep both of them in the same directory. 

Step B - Add SPRMessengerClient to your Podfile and run the following code

pod install

target :YourTargetName do

 pod 'SPRMessengerClient', :podspec => <path_to_messenger_folder>/SPRMessengerClient.podspec

end

​Step C - If your app enabled bitcode, add this pod installer script in your podfile

post_install do |installer|

installer.pods_project.targets.each do |target|

  target.build_configurations.each do |config|

    config.build_settings['ENABLE_BITCODE'] = 'YES'

  end

end

end

Note: Please raise a support ticket(tickets@sprinklr.com) or reach out to SM for Sprinklr Messenger Plugin

Step 2: Add Permissions 

Include the following permissions in info plist file, if you are supporting upload and download media functionality in messenger:

<key>NSCameraUsageDescription</key>
<string>Messenger app requires access to the camera to capture the photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Messenger app requires access to the microphone to record video.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Messenger app requires access to the photos library.</string>

Above permissions are required by Apple for all apps that access the photo library or use the camera/microphone

Step 3: Initialize the Messenger

Now in step 3, you will need to call the takeOff method with the appId provided by Sprinklr.
Steps for Anonymous users and authenticated users are explained below: 

For Anonymous Users

For anonymous chats you can initialize the messenger using the takeOff method. Behind the scenes we will automatically create the anonymous user for the messenger and initialize the flow for the same. Please note that the takeOff method should be called once in the application lifecycle. You can use separate methods for updating the user or various information in the messenger which are explained in other sections. For the best performance takeOff should be called at the root of the application or as early as possible in your application flow.

Swift

import SPRMessengerClient


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let config = SPRMessengerConfig();
        config.appId = "SPR_APP_ID" // This will be provided by sprinklr

        config.appKey = "com.sprinklr.messenger.release"  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

        config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 
        config.deviceId = "UNIQUE_DEVICE_ID"; // unique key

        config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

        config.locale = "SPR_LOCALE"; // default value is en

config.skin = "MODERN"; // default value is MODERN, options: CLASSIC | MODERN 

config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK


        SPRMessenger.takeOff(config)
}

​Objective C

#import <SPRMessengerClient/SPRMessenger.h>

#import <SPRMessengerClient/SPRMessengerConfig.h>

#import <SPRMessengerClient/SPRMessengerViewController.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  SPRMessengerConfig *config = [SPRMessengerConfig new];

  config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr

  config.appKey = @"com.sprinklr.messenger.release". // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

  config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 

  config.deviceId = @"UNIQUE_DEVICE_ID";

  config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

  config.locale = @"SPR_LOCALE"; // default value is en

config.skin = @"MODERN"; // default value is MODERN, options: CLASSIC | MODERN

  config.themeMode = @"DEFAULT";  // default value is DEFAULT, options: DEFAULT | DARK

  [SPRMessenger takeOff:config];

}

For Authenticated Users

This step is done after the user logs in successfully and completes the authentication process within the application and after the authentication process, it should be passed in Sprinklr including the app id. In case, a user is not logged in case (s)he has never used the application then an anonymous user can be created for the same. 

After the authentication process, the client should pass the user bean, the application ID, the messenger activity with the information that include so that Sprinklr can begin the initial setup process in the background- 

id

firstName

lastName

profileImageUrl

phoneNo

Email

Swift

import SPRMessengerClient


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let config = SPRMessengerConfig();
        config.appId = "SPR_APP_ID" // This will be provided by sprinklr

        config.appKey = "com.sprinklr.messenger.release"  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

        config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 
        config.deviceId = "UNIQUE_DEVICE_ID";

        config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

        config.locale = "SPR_LOCALE"; // default value is en

config.skin = "MODERN"; // default value is MODERN, options: CLASSIC | MODERN 
        config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK
        

        let user = SPRMessengerUser();
        user.id = "12345";
        user.firstName = "John";
        user.lastName = "Doe";
        user.phoneNo = "9876543210";
        user.email = "John.Doe@example.com";
        user.profileImageUrl = "https://example.com/profilePic.jpg";
        user.hashValue = "f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22";
        config.user = user;
        SPRMessenger.takeOff(config)
}

Objective C

#import <SPRMessengerClient/SPRMessenger.h>

#import <SPRMessengerClient/SPRMessengerConfig.h>

#import <SPRMessengerClient/SPRMessengerViewController.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  SPRMessengerConfig *config = [SPRMessengerConfig new];

  config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr

  config.appKey = @"com.sprinklr.messenger.release" // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

  config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 

  config.deviceId = @"UNIQUE_DEVICE_ID";

  config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

  config.locale = @"SPR_LOCALE"; // default value is en

config.skin = @"MODERN"; // default value is MODERN, options: CLASSIC | MODERN 

  config.themeMode = @"DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK

 

  SPRMessengerUser *user = [SPRMessengerUser new];

  user.id = @"12345";

  user.firstName = @"John";

  user.lastName = @"Doe";

  user.phoneNo = @"9876543210";

  user.email = @"John.Doe@example.com";

  user.profileImageUrl = @"https://example.com/profilePic.jpg";

  user.hashValue = @"f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22";

  config.user = user;

  [SPRMessenger takeOff:config];

}

Note: userID and hash are mandatory parameters and hash should be generated for every change in user object. To know the procedure of how to generate Hash, check Step 9: Generate User Hash

For Authenticated Custom Users

This step is done to create a custom user account using custom or specific attributes. In other words, it involves creating user accounts with personalized details or characteristics 
Below is the example to initiate the process with custom attributes and Hash, where you can  pass the attributes values: 

  • Custom Attribute 1 

  • Custom Attribute 2 

  • Hash 

Note: If you wish to implement a Custom User Authentication Flow, kindly get in touch with the Sprinklr Team to initiate discussions about the implementation process. 

Swift  

let config = SPRMessengerConfig(); 
config.appId = "SPR_APP_ID" // This will be provided by sprinklr 

config.appKey = "com.sprinklr.messenger.release"  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 
config.deviceId = "UNIQUE_DEVICE_ID";

config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2) 

config.locale = "SPR_LOCALE"; // default value is en 
config.skin = "MODERN"; // default value is MODERN, options: CLASSIC | MODERN 

config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK

 

config.customUser = ["customAttribute1": "value1", "customAttribute2": "value2", "hash": "8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"]  // Add your custom attributes

 

SPRMessenger.takeOff(config); 

Objective C 

SPRMessengerConfig *config = [[SPRMessengerConfig alloc] init]; 

 
  config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr 

  config.appKey = @"com.sprinklr.messenger.release"  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

  config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 

  config.deviceId = @"UNIQUE_DEVICE_ID"; 

  config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2) 

  config.locale = @"SPR_LOCALE"; // default value is en 
  config.skin = @"MODERN"; // default value is MODERN, options: CLASSIC | MODERN 

  config.themeMode = @"DEFAULT";  // default value is DEFAULT, options: DEFAULT | DARK

config.customUser = @{@"customAttribute1": @"value1", @"customAttribute2": @"value2", @"hash": @"8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"}  // Add your custom attributes

 

[SPRMessenger takeOff:config]; 

 

Step 4: Show Messenger

Add the following code in the onClick event of the button you want to use to launch the chat

  1. Swift

    let viewController = SPRMessengerViewController.init(launchOptions: launchOptions);

    viewController.modalPresentationStyle = .fullScreen
    self.present(viewController, animated: true, completion: nil)

  2. Objective C

    [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions]
    viewController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:viewController animated:YES completion:nil];

Note: You need to pass launchOptions when opening sprinklr messenger from notification tap which is explained in Step 5 Push Notifications, else you can pass launchOptions as nil.

Step 5: Messenger Configurations

1) Update User

User attributes can be updated by calling, follow the below steps: 

Swift

let user = SPRMessengerUser();
user.id = "12345";
user.firstName = "John";
user.lastName = "Doe";
user.phoneNo = "9876543210";
user.email = "John.Doe@example.com";
user.profileImageUrl = "https://example.com/profilePic.jpg";
user.hashValue = "fa91cafc6522662a70ad521ae050acce996190aa38b72ac66b48c68d4666ba38";
SPRMessenger.shared().updateUser(user)

​Objective C

SPRMessengerUser *user = [SPRMessengerUser new];

user.id = @"12345";

user.firstName = @"John";

user.lastName = @"Doe";

user.phoneNo = @"9876543210";

user.email = @"John.Doe@example.com";

user.profileImageUrl = @"https://example.com/profilePic.jpg";

user.hashValue = @"f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22";

[[SPRMessenger shared] updateUser:user];

Note: userID and hash are mandatory parameters and hash should be generated for every change in user object. 

2) Update Custom User 

Custom User attributes can be updated by calling, follow the below steps -- 

Swift

let customUser = ["customAttribute1": "value1", "customAttribute2": "value2", "hash": "8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"

 

SPRMessenger.shared().updateCustomUser(customUser) 

Objective C

NSDictionary *customUser = @{@"customAttribute1": @"value1", @"customAttribute2": @"value2", @"hash": @"8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"
 
[[SPRMessenger shared] updateCustomUser:customUser];

3) Update Language

To update the user language use below function:

  1. Swift

    SPRMessenger.shared().updateLocale(locale)

  2. Objective C

    [[SPRMessenger shared] updateLocale:locale];

Sprinklr messenger supports the following languages: Arabic, Bokmal, Chinese, English, Thai, Turkish, Vietnamese, Portuguese, Spanish, Indonesian, Japanese, Korean, French. 

Few languages with limited availability are Albanian, Norwegian, Bosnian, Chinese (traditional), Chinese (honk-kong), Croatian, Czech, Danish, Dutch, Estonian, Finnish, German, Hebrew, Hungarian, Italian, Latvian, Lithuanian, Macedonian, Malayalam, Polish, Romanian, Serbian, Slovak, Slovanian, Swedish.

4) Cleanup

You can logout the user and cleanup the associated data from the application by calling logout

  1. Swift

    SPRMessenger.shared().logout()

  2. Objective C

    [[SPRMessenger shared] logout];

5) Customize Messenger Landing Screen

By default, the messenger view opens with a home page displaying all conversations. However, you can customize this behavior and launch MessengerView with a single conversation view. Below are the options for customization which you can use: 

Default View

Sprinklr Live Chat comprises of two screens: the home screen and the conversation screen. By default, both the screens are accessible when Live Chat opens.

The following are the various ways you can customize the default view according to your use case:

By default, Live Chat opens on the home screen, including the conversation screen. Use the following code to open the defualt view:

Swift

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions)

Objective C

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions];

When Live Chat is set to default view with NEW_CONVERSATION, it initiates a new conversation on behalf of the user, starting with the welcome messages set in the application builder.

To continue any existing conversations, users must return to the home screen.

Swift

let chatInitialisationContext = ["landingScreen": "NEW_CONVERSATION"]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"landingScreen":@"NEW_CONVERSATION"

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

When Live Chat is set to default view with LAST_CONVERSATION, it opens the last conversation that is still open. If there are no open conversation, it initiates a new conversation on behalf of the user starting with the welcome messages set in the application builder.

To continue any existing conversations, users must return to the home screen.

Swift

let chatInitialisationContext = ["landingScreen": "LAST_CONVERSATION"]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{

@"landingScreen":@"LAST_CONVERSATION"

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use the following code to start a new conversation with a custom message from your brand or user, tailored to your specific needs.

Swift

let initialMessages = [

[

"message": "This is a brand message",

"isSentByUser": false

],

"This is another brand message",

[

"message": "This is a user message",

"isSentByUser": true

]

] as [Any]

let chatInitialisationContext = [

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages

] as [String : Any]

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];
NSDictionary *brandMessage = @{

@"message": @"This is a brand message",

@"isSentByUser": @NO

};

[initialMessages addObject:brandMessage];


NSString *anotherBrandMessage = @"This is another brand message";

initialMessages addObject:anotherBrandMessage];
NSDictionary *userMessage = @{

@"message": @"This is a user message",

@"isSentByUser": @YES

};

[initialMessages addObject:userMessage];


NSDictionary *chatInitialisationContext = @{ @"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy] };

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

When you want to open a specific conversation (one that’s undeleted and has the most recent published message) for the user, use the captured ID (obtained by listening to events indicating the ongoing conversation).

Swift

let chatInitialisationContext = ["landingScreen": "EXISTING_CONVERSATION", "params": ["conversationId": "id_of_conversation"]]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"scope": @"CONVERSATION", @"landingScreen":@"EXISTING_CONVERSATION", @"params":@{

@"conversationId": @"id_of_conversation"

}};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use this code to open a new conversation and automatically start a video call, enabling face-to-face interaction.

Swift

var initialMessages = [Any]()
let chatInitialisationContext = [

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages,

"additional": [

"callType": "VIDEO"

]

] as [String : Any]
let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];


NSDictionary *chatInitialisationContext = @{

@"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy], @"additional": @{

@"callType": @"VIDEO"

}

};
SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use the following code to open a new conversation with an automatically initiated audio call for real-time voice communication.

Swift

var initialMessages = [Any]()
let chatInitialisationContext = [

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages,

"additional": [

"callType": "AUDIO"

]

] as [String : Any]

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];
NSDictionary *chatInitialisationContext = @{

@"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy], @"additional": @{

@"callType": @"AUDIO"

}

};
SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Single Conversation View

You can choose to display the single conversation view and hide the home screen completely.

The following are the various ways you can customize the single conversation view according to your use case:

Use the following code to display only the conversation screen in Live Chat and hide the home screen.

Note: The scope:'CONVERSATION' option limits Live Chat to only the conversation screen.

Swift

let chatInitialisationContext = ["scope": "CONVERSATION"]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"scope": @"CONVERSATION"

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

When live chat is set to single conversation view with NEW_CONVERSATION, it initiates a new conversation on behalf of the user, starting with the welcome messages set in the application builder.

It will always open a conversation pane by initiating a new conversation, and will eventually hide any previous chats that are currently open.

Swift

let chatInitialisationContext = ["scope": "CONVERSATION", "landingScreen": "NEW_CONVERSATION"]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"scope": @"CONVERSATION", @"landingScreen":@"NEW_CONVERSATION"

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

When Live Chat is set to single conversation view with LAST_CONVERSATION, it opens the last conversation that is still open. If there are no open conversation, it initiates a new conversation on behalf of the user starting with the welcome messages set in the application builder.

Swift

let chatInitialisationContext = ["scope": "CONVERSATION", "landingScreen": "LAST_CONVERSATION"]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"scope": @"CONVERSATION", @"landingScreen":@"LAST_CONVERSATION"

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use the following code to open the single conversation view and start a new conversation with a custom message from your brand or user.

Swift

let initialMessages = [

[

"message": "This is a brand message",

"isSentByUser": false

],

"This is another brand message",

[

"message": "This is a user message",

"isSentByUser": true

]

] as [Any]


let chatInitialisationContext = [

"scope": "CONVERSATION",

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages

] as [String : Any]

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];
NSDictionary *brandMessage = @{

@"message": @"This is a brand message",

@"isSentByUser": @NO

};

[initialMessages addObject:brandMessage];

NSString *anotherBrandMessage = @"This is another brand message";

initialMessages addObject:anotherBrandMessage];
NSDictionary *userMessage = @{

@"message": @"This is a user message",

@"isSentByUser": @YES

};

[initialMessages addObject:userMessage];


NSDictionary *chatInitialisationContext = @{ @"scope": @"CONVERSATION", @"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy] };

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

When you want to open a specific conversation without home page (one that’s undeleted and has the most recent published message) for the user, use the captured ID (obtained by listening to events indicating the ongoing conversation).

Swift

let chatInitialisationContext = ["scope": "CONVERSATION", "landingScreen": "EXISTING_CONVERSATION", "params": ["conversationId": "id_of_conversation"]]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSDictionary *chatInitialisationContext = @{
@"scope": @"CONVERSATION", @"landingScreen":@"EXISTING_CONVERSATION", @"params":@{

@"conversationId": @"id_of_conversation"

}};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use the following code to open the single conversation view with a new conversation and automatically start a video call for direct face-to-face communication.

Swift

var initialMessages = [Any]()
let chatInitialisationContext = [

"scope": "CONVERSATION",

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages,

"additional": [

"callType": "VIDEO"

]

] as [String : Any]


let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];
NSDictionary *chatInitialisationContext = @{

@"scope": @"CONVERSATION", @"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy], @"additional": @{

@"callType": @"VIDEO"

}

};

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

Use the following code to open the single conversation view with a new conversation and automatically start an audio call for real-time voice communication.

Swift

var initialMessages = [Any]()
let chatInitialisationContext = [

"scope": "CONVERSATION",

"landingScreen": "NEW_CONVERSATION",

"initialMessages": initialMessages,

"additional": [

"callType": "AUDIO"

]

] as [String : Any]

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext)

Objective C

NSMutableArray *initialMessages = [NSMutableArray new];
NSDictionary *chatInitialisationContext = @{

@"scope": @"CONVERSATION", @"landingScreen":@"NEW_CONVERSATION", @"initialMessages": [initialMessages copy], @"additional": @{

@"callType": @"AUDIO"

}

};


SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext];

6) Capture Customer Context When Starting a New Conversation from Custom View

When chat is being opened from a custom view, sometimes you might want to capture additional context on the conversation/case. 

Example - A button called “Know More about this laptop”  near a laptop product which opens a chat with a predefined contextual welcome message - “Hi there! It looks like you are interested in buying a laptop”. At the same time, you might want to set the case custom fields indicating the “product category: laptop”, “case type: inquiry”.

To do this,

  1. Create the case custom fields and note down their field name

  2. Pass conversationContext to chatInitialisationContext*: when opening a new conversation directly (5ea7fa9e87651f356209878f and 5eb7fa9e87651f356219348e are the two custom field names). All the field values should be passed as an array of strings.

    1. Swift

      let conversationContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];

      let chatInitialisationContext = ["conversationContext": conversationContext] as [String : Any]

    2. Objective C

      NSDictionary *conversationContext = @{
          @"5ea7fa9e87651f356209878f": @[@"laptop"],
          @"5eb7fa9e87651f356219348e": @[@"inquiry"]

      };

      NSDictionary *chatInitialisationContext = @{ 

          @"conversationContext": conversationContext 

      };

*Note: chatInitialisationContext is explained in the previous section.

7) Capture Customer Context from the Application on All Cases of the User

Sometimes you might want to pass some contextual information in case custom fields for all conversations started by the user.

To do this,

  1. Create the case custom fields and note down their field name

  2. You can pass these values in clientContext in the takeOff method called in step 5. (5e281d040844e435b is the custom field name). All the field values should be passed as an array of strings.

    1. Swift

      let clientContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];
      config.clientContext = clientContext

    2. Objective C

      NSDictionary *clientContext = @{
          @"5ea7fa9e87651f356209878f": @[@"laptop"],
          @"5eb7fa9e87651f356219348e": @[@"inquiry"]
      };
         
      config.clientContext = clientContext;

  3. You can also update the client context on run time by calling the following method: All the field values should be passed as an array of strings.

    1. Swift

      let clientContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];


      SPRMessenger.shared().updateClientContext(clientContext)

    2. Objective C

      NSDictionary *clientContext = @{
          @"5ea7fa9e87651f356209878f": @[@"laptop"],
          @"5eb7fa9e87651f356219348e": @[@"inquiry"]
      };
         
      [[SPRMessenger shared] updateClientContext:clientContext];

8) Update Conversation Context (Case Custom Field) on Demand

At times you might want to update the value of conversation context/case custom field during or after a conversation. 

  1. Create the case custom fields and note down their field name

  2. All the field values should be passed as an array of strings.

    1. Swift

       let conversationContext = ["context": ["5ea7fa9e87651f356209878f": ["laptop"],"5eb7fa9e87651f356219348e": ["inquiry"]]];

      SPRMessenger.shared().updateConversationContext(conversationContext)

    2. Objective C

        NSDictionary *conversationContext = @{

          @"context": @{

            @"5ea7fa9e87651f356209878f": @[@"laptop"],

            @"5eb7fa9e87651f356219348e": @[@"inquiry"]

          }

        };

       

        [[SPRMessenger shared] updateConversationContext:conversationContext];

9) Update the profile context within Profile Custom Fields 

When chat is being opened from a custom button or hyperlink, sometimes you might want to capture some context on the profile/user during the conversation or after the conversation.

To do this, 

  1. Create the profile custom fields and note down their field name. 

  2. Whenever you want to update the profile custom field, call the following and pass the information for profile level custom fields

    1. Swift

      let userContext = ["5ea7fa9e87651f356209878f":
      ["laptop"],"5eb7fa9e87651f356219348e": ["inquiry"]];

      SPRMessenger.shared().updateUserContext(userContext)

    2. Objective C

      NSDictionary *userContext = @{
          @"5ea7fa9e87651f356209878f":
      @[@"laptop"],
          @"5eb7fa9e87651f356219348e":
      @[@"inquiry"]
      };

      [[SPRMessenger shared] updateUserContext:userContext];

10) Close Messenger

You can close messenger from the main application by calling closeMessenger.

  1. Swift

    SPRMessenger.shared().close()

  2. Objective C

    [[SPRMessenger shared] closeMessenger];

11) Add Delegate to Listen to External Events from Messenger

   Add following piece of code wherever you want to listen for the external events.

  1. Swift

    Add messenger delegate where you have defined your take off method:

    class ClassName: SPRMessengerDelegate

    Inside the initialisation function of the class add after takeoff:

    let sprMessenger = SPRMessenger.shared()
    sprMessenger.delegate = self

    And finally add function to listen to external events payload:

    func handleExternalAction(_ payload: [AnyHashable : Any]) {}

  2. Objective C

    At top of the class add:

    @interface ClassName () <SPRMessengerDelegate>
    @end

    Inside the initialisation function of the class add after takeoff:

    SPRMessenger* sprMessenger = [SPRMessenger shared];
    sprMessenger.delegate = self;

    And finally add function to listen to external events payload:

    - (void) handleExternalAction:(NSDictionary*) payload {}

12) Get Number of Open Conversations  

Sometimes you might want to hide the live chat widget based on the number of open conversation. To do this,

  1. Call the the below function to get the number of open conversations

    1. Swift 

       SPRMessenger.shared().getNumberOfOpenConversations() 

    2. Objective C

      [[SPRMessenger shared] getNumberOfOpenConversations]; 

  2. Add Delegate to listen to the output of above function 

    1. Swift

      Add messenger delegate where you have defined your take off method:

      class ClassName: SPRMessengerDelegate

      Inside the initialisation function of the class add after takeoff:

      let sprMessenger = SPRMessenger.shared()
      sprMessenger.delegate = self

      And finally add function to listen to external events payload:

      func onUpdateNumberOfOpenConversations(_ count: NSNumber) {} 

    2. Objective C

      At top of the class add:

      @interface ClassName () <SPRMessengerDelegate>
      @end

      Inside the initialisation function of the class add after takeoff:

      SPRMessenger* sprMessenger = [SPRMessenger shared];
      sprMessenger.delegate = self;

      And finally add function to listen to external events payload:

      - (void) onUpdateNumberOfOpenConversations:(NSNumber*) count {} 

13) Get Number of Unread Messages

You can keep track of changes in the total number of unread messages in conversations. To do this:

  1. Add Delegate to listen to the updates in unread messages count

    1. Swift

      Add messenger delegate where you have defined your take off method:

      class ClassName: SPRMessengerDelegate

      Inside the initialisation function of the class add after takeoff:

      let sprMessenger = SPRMessenger.shared()
      sprMessenger.delegate = self

      And finally add function to listen unread messages count update payload:

      func onUpdateUnreadMessagesCount(_ response: SPRMessengerUnreadMessagesCountResponse) { 

          let success = response.success 

       

          if success { 

              let unreadMessagesCount = response.unreadMessagesCount; 

        // Add your logic here 

          } else { 

              if let error = response.error { 

                let errorMessage = error.localizedDescription; 

                // Add your logic here 

              } 

          } 

             }

    2. Objective C

      At top of the class add:

      @interface ClassName () <SPRMessengerDelegate>
      @end

      Inside the initialisation function of the class add after takeoff:

      SPRMessenger* sprMessenger = [SPRMessenger shared];
      sprMessenger.delegate = self;

      And finally add function to listen to external events payload:

      - (void)onUpdateUnreadMessagesCount:(nonnull SPRMessengerUnreadMessagesCountResponse*)response { 

        BOOL success = response.success; 

        if (success) { 

           NSInteger *unreadMessagesCount = response.unreadMessagesCount; 

          // Add your logic here 

           

        } else { 

          NSError *error = response.error; 

          NSString *errorMessage = [error localizedDescription]; 

          // Add your logic here 

        } 

      }

  2. You can also trigger the event to get the current unread messages count by calling following method:

    1. Swift

      SPRMessenger.shared().getUnreadMessagesCount ()

    2. Objective C

      [[SPRMessenger shared] getUnreadMessagesCount];

Note: You would receive the current unread messages count response in the onUpdateUnreadMessagesCount method of the delegate you attached earlier.

14) Add Messenger Analytics Handler delegate to Listen to tracking events and screen 

Add following piece of code wherever you want to listen for the analytics events 

Swift 

Add analytics handler where you have defined your take off method: 

class ClassName: SPRMessengerAnalyticsHandler  

Inside the initialisation function of the class add after takeoff: 

let sprMessenger = SPRMessenger.shared() 
sprMessenger.analyticsHandler= self 

And finally add below functions to listen to track event and screen : 

func trackEvent(_ eventType: String, withPayload payload: String) {} 

func trackScreen(_ screenName: String) 

Objective C 

At top of the class add:

@interface ClassName () <SPRMessengerAnalyticsHandler> 
@end 

Inside the initialisation function of the class add after takeoff: 

SPRMessenger* sprMessenger = [SPRMessenger shared]; 
sprMessenger.analyticsHandler = self; 

And finally add below functions to listen to track event and screen : 

- (void)trackEvent:(nonnull NSString *)eventType withPayload:(nonnull NSString *)payload {} 

- (void)trackScreen:(nonnull NSString *)screenName {} 

15) Add Messenger Events Listener to SDK events 

The following events can be listened: 

Event Type:

  1. BOOT_FAILED

  2. BOOT_STARTING

  3. BOOT_COMPLETE

  4. USER_LOGOUT

  5. SSL_CERTIFICATE

  6. UPDATE_USER_FAILED

  7. UPDATE_USER_SUCCESS

  8. UPDATE_USER_CONTEXT_FAILED

  9. UPDATE_CLIENT_CONTEXT_FAILED

  10. ANONYMOUS_SESSION_CREATION_STARTING

  11. ANONYMOUS_SESSION_CREATION_SUCCESS

  12. ANONYMOUS_SESSION_CREATION_FAILED

  13. UPDATE_USER_STARTING

Event Type: INTERNET_CONNECTION_STATUS_CHANGED

Event Type:

  1. PUSH_NOTIFICATION_REGISTRATION_EXISTS

  2. PUSH_NOTIFICATION_REGISTRATION_SUCCESS

  3. PUSH_NOTIFICATION_REGISTRATION_FAILED

  4. PUSH_NOTIFICATION_UNREGISTRATION_SUCCESS

  5. PUSH_NOTIFICATION_UNREGISTRATION_FAILED

Event Type:

  1. NEW_CONVERSATION_INITIATION_FAILED

  2. CONVERSATION_CLOSED

  3. CONVERSATION_DELETED

  4. CONVERSATION_CLOSE_FAILED

  5. CONVERSATION_DELETE_FAILED

  6. CONVERSATION_CLOSED_BY_AGENT

Add following piece of code wherever you want to listen for the messenger events 

Swift 

Add messenger delegate where you have defined your take off method: 

class ClassName: SPRMessengerEventsHandler 

Inside the initialisation function of the class add after takeoff 

let sprMessenger = SPRMessenger.shared() 
sprMessenger.eventsListener = self 

 And finally add function to listen to events: 

func onEvent(_ eventGroup: String, withEventType eventType: String, andPayload payload: String) {} 

Objective C 

At top of the class add: 

@interface ClassName () <SPRMessengerEventsHandler> 
@end

Inside the initialisation function of the class add after takeoff: 

SPRMessenger* sprMessenger = [SPRMessenger shared]; 
sprMessenger.eventsListener = self; 

And finally add function to listen to events: 

- (void)onEvent:(nonnull NSString *)eventGroup withEventType:(nonnull NSString *)eventType andPayload:(nonnull NSString *)payload {}

 

16) Add Events Logger to SDK Events

The provided code snippet establishes a logging system which can handle logging events at different levels. This setup enables us to efficiently track and manage various events within the app.

Swift

Add logger transport where you have defined your take off method:

class ClassName: SPRLoggerTransport

Before calling takeOff, add loggerConfig:

let loggerConfig = SPRLoggerConfig()

loggerConfig.enableLogs = true // required to enable logs

loggerConfig.level = SPRLogLevel.INFO // optional, default level is SPRLogLevel.INFO

loggerConfig.loggerTransport = self

config.loggerConfig = loggerConfig

​Note: The Swift compiler automatically removes the common prefix (SPR_) for enum members, hence they can be accessed without adding the SPR_ prefix. (example: SPRLogLevel.INFO)

And finally add a custom logger transport function:

public func write(_ level: UnsafeMutablePointer<SPRLogLevel>, withLogs logs: [Any]) {
// your custom logger transport

}

 Objective C

Add logger transport where you have defined your take off method:

@interface ClassName ()
<SPRLoggerTransport>

@end

Before calling takeOff, add loggerConfig:

SPRLoggerConfig *loggerConfig = [[SPRLoggerConfig alloc] init];

loggerConfig.level = SPR_INFO;

loggerConfig.enableLogs = YES;

loggerConfig.loggerTransport = self;

config.loggerConfig = loggerConfig;

 

And finally add a custom logger transport function:

- (void) write:(nonnull SPRLogLevel*)level withLogs:(nonnull NSArray *)logs {

// your custom logger transport

}

SPR_OFF = 0

SPR_FATAL = 1

SPR_ERROR = 2

SPR_WARN = 3

SPR_INFO = 4

SPR_DEBUG = 5

SPR_TRACE = 6

SPR_ALL = 7

17) Update Theme Mode for User on demand

You can update the theme mode on demand:

Swift

SPRMessenger.shared().updateThemeMode("DARK") // options: DEFAULT | DARK

Objective C

[[SPRMessenger shared] updateThemeMode:(@"DARK")]; // options: DEFAULT | DARK

Note: Upon invoking the updateThemeMode() method, a confirmation alert will prompt the user to reload the app for the changes in theme to take effect. Furthermore, the parent application should send the updated theme within the configuration while chat initialization

18)Configure your Status Card

Note: To get this capability enabled, please reach out to our support team at tickets@sprinklr.com, providing the live chat application ID. Status Card can be enabled only if you are using the modern skin version of live chat widget.

 

Using Status Cards, you can update your customers about the health of a key resource. This key resource could be a tool or service that they interact with frequently. By showing the status of this resource directly, customers don’t have to reach to agents repeatedly. Hence, this improves the customer experience while reducing agent workload

 

Once status card is enabled for your Livechat widget, you can update the status card by using the following:

Swift

let details = SPRMessengerWidgetDetailsConfig();
details.title = "Your title, %%[status]"
details.desc = "Your description, %%[updatedAt]"
details.updatedAt = Int(Date().timeIntervalSince1970 * 1000)
details.status = SPRStatus.ALL_SYSTEMS_OPERATIONAL
SPRMessenger.shared().updateWidget("WIDGET_ID", withDetails: details) // Same ID configured in the Live Chat builder must also be utilized here

Note: The Swift compiler automatically removes the common prefix (SPR_) for enum members, hence they can be accessed without adding the SPR_prefix. (example: SPRStatus.ALL_SYSTEMS_OPERATIONAL)
Objective C

SPRMessengerWidgetDetailsConfig *widgetDetails = [[SPRMessengerWidgetDetailsConfig alloc] init];

widgetDetails.title = @“Your title, %%[status]";

widgetDetails.desc = @“Your description, %%[updatedAt]";

widgetDetails.status = SPR_MAJOR_SYSTEM_OUTAGE;

widgetDetails.updatedAt = [[NSDate date] timeIntervalSince1970] * 1000;

[[SPRMessenger shared] updateWidget:@“WIDGET_ID” withDetails:widgetDetails]; // Same ID configured in the Live Chat builder must also be utilized here

You can use the following placeholders for title and description:

a.     %%[updatedAt] --> Placeholder for formatted time

b.     %%[status] --> Placeholder for Status, mentioned below in the table as SPRStatus

​​


Status Placeholder Value


Icon



SPRStatus



All Systems Operational





SPR_ALL_SYSTEMS_OPERATIONAL



Service Under Maintenance





SPR_SERVICE_UNDER_MAINTENAwNCE



Partially Degraded Service





SPR_PARTIALLY_DEGRADED_SERVICE



Degraded System Service





SPR_DEGRADED_SYSTEM_SERVICE



Partial System Outage





SPR_ MINOR_SYSTEM_OUTAGE



Minor System Outage





SPR_ PARTIAL_SYSTEM_OUTAGE



Major System Outage





SPR_ MAJOR_SYSTEM_OUTAGE


 

19) Disable Attachments for Customer

You can prevent customers from adding attachments in the chat by hiding the attachment icon from the chat widget.

To do this, you can pass disableAttachment:true in the takeOff method

Swift

config.disableAttachment = true  // by default, attachments are enabled

 Objective C

config.disableAttachment = YES; // by default, attachments are enabled

20) Integrate Your Brand's Custom Header in Live Chat 

Enhance your live chat experience by incorporating your own custom header. This allows you to replace Live Chat default header with one that aligns with your brand identity, creating a consistent and seamless experience for your users. 

Swift  

let chatInitialisationContext = [ 
 “disableHeader”: false, // Default: false. To disable Sprinklr's header, set to true 

 “isRenderedAsFullView”: true // Default: true. If set to false, the brand must manage device top insets 

  

let viewController = SPRMessengerViewController.init(launchOptions: launchOptions, andChatInitialisationContext: chatInitialisationContext);  

Objective C 

NSDictionary *chatInitialisationContext = @{  

   @“disableHeader”: @NO, // Default: NO. To disable Sprinklr's header, set to YES 

   @“isRenderedAsFullView”: @YES // Default: YES. If set to NO, the brand must manage device top insets 

}; 

  

SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions andChatInitialisationContext:chatInitialisationContext]; 

 

21) Implement Back Button Handling to Control Hardware Back Button 

Utilize the below method to handle the back action within your chat application. This function allows users to seamlessly navigate back to the previous screen, enhancing the overall user experience by providing intuitive and efficient navigation 

Swift 

SPRMessenger.shared().goBack() // Handles the back action 

Objective C 

[[SPRMessenger shared] goBack]; // Handles the back action 

 

22) Close Conversation 

Use the method below to close a conversation on live chat. This feature allows brands to efficiently handle conversation endings, providing control over when and how interactions are closed. Apply this method only on the conversation screen when the case is open to ensure a seamless transition for users as conversations end. 

Swift 

SPRMessenger.shared().closeConversation()

Objective C 

[[SPRMessenger shared] closeConversation];

 

​23) Close All Conversations 

Use the method below to close all conversation on live chat. This option is visible to users with open cases, if there are no cases or all existing cases are already closed then user will not be able to see this option.

Swift 

SPRMessenger.shared().closeAllConversations()

Objective C 

[[SPRMessenger shared] closeAllConversations];

 

24) Delete Conversation 

Use this method to delete a conversation in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions. Apply this method only on the conversation screen to manage deletions effectively. 

Swift 

SPRMessenger.shared().deleteConversation() 

Objective C 

[[SPRMessenger shared] deleteConversation]; 

25) Delete All Conversations 

Use this method to delete all the conversations in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions. Apply this method only on the home screen to manage deletions effectively. 

Swift 

SPRMessenger.shared().deleteAllConversations()

Objective C 

[[SPRMessenger shared] deleteAllConversations];

 

26) Clear User Session

You can now enable users to clear their session details. When a user clears their session, any new conversations will be treated as if they are from a completely new user. This feature is especially useful for users interacting with your brand in public spaces or over a public network.

Swift 

SPRMessenger.shared().clearSession()

Objective C 

[[SPRMessenger shared] clearSession];

​27) Use a Custom Font

You can use a custom font in your Live Chat app to ensure consistent branding across your applications.

​To use a custom font in Live Chat, follow these steps:

  1. Link your custom font files in your iOS project natively, such that the fonts are available throughout the project. For steps, see iOS documentation.

  2. Open a Sprinklr support ticket at tickets@sprinklr.com. In the support ticket, mention the font file names and the supported font weights for the texts. Refer to the following table for the supported font weights.

Note: Ensure you provide at least one of the supported font weights in the support ticket. If you provide a single font weight, it will be applied throughout the app, overriding all the other font weights.

Similarly, if any of the font weights are not mentioned in the support ticket, the font weight closest to the non-mentioned font weight will be applied in the app.

Supported font weights​

The following table lists the supported font weights:

Font weight

Description

Light

The light font weight is for subtle accents, secondary text, and areas where minimal emphasis is required.

Regular

The standard font weight for most text elements.

Medium

Medium is used for subheadings, labels, or emphasis on certain text sections without the bold impact.

Semibold

Works well for headings, button labels, or any text that needs more attention but doesn’t require bold styling.

Bold

Bold is designed for titles, primary headings, and call-to-action elements.

Step 6: Push Notifications

For more details on mobile push notifications, please refer here

Prerequisite

  1. APNS certificate (P12) along with its credentials

Note:

  • APNS certificate (P12) and its credentials must be different for staging/prod env

  • If you are testing the push notification setup on prod mobile application(iOS), plesae ensure to use Android release build

Configuration

To enable push notifications, please raise a support ticket to tickets@sprinklr.com with the following information:

  1. APNS certificate (P12) along with its credentials

  2. Live Chat AppID

  3. Partner ID

  4. Env

  •  Register/Unregister for Push Notifications

    You can register the messenger for sending push notifications by providing push token received from apns/fcm as below:

    1. Swift

      SPRMessenger.pushManager().setRegistrationToken(token)

    2. Objective C

      [[SPRMessenger pushManager] setRegistrationToken: token];

    You can unregister for messenger push notifications by sending empty token as below:

    1. Swift

      SPRMessenger.pushManager().setRegistrationToken("")

    2. Objective C

      [[SPRMessenger pushManager] setRegistrationToken: @""];

  • Handle Messenger Push Notifications

    1. Once you have registered for messenger push notifications then you might receive notifications from your platform as well as messenger. To check if notification is messenger notification you can check as below:

    1. Swift

      let isMessengerNotification = SPRMessenger.pushManager().canHandlePushEvent(userInfo)

    2. Objective C

      BOOL isMessengerNotification = [[SPRMessenger pushManager] canHandlePushEvent: userInfo]

    2. Once you have identified if the notification is messenger notification you need to follow the below step to handle push notification.

    1. Swift

      SPRMessenger.pushManager().handlePushEvent(userInfo)

    2. Objective C

      [[SPRMessenger pushManager] handlePushEvent: userInfo]

    3. You can now open the conversation screen directly from a push notification when the app is in the background and the Messenger SDK is mounted.

    • Swift

      SPRMessenger.pushManager().handlePushNotification(userInfo)

    • Objective C

      [[SPRMessenger pushManager] handlePushNotification: userInfo]

  • Open Messenger View with Initial Notification

    Open live chat view with initial notification: Messenger view can be presented with initial notification as the result of opening from notifications or in-app notification banners:

  • Swift

    let launchOptions = ["type": "NOTIFICATION", "data": notificationData]

    let viewController = SPRMessengerViewController.init(launchOptions: launchOptions);

  • Objective C

    NSDictionary *launchOptions = @{ 

       @"type": @"NOTIFICATION", @"data":notificationData

    };

    SPRMessengerViewController *viewController = [[SPRMessengerViewController alloc] initWithLaunchOptions:launchOptions];

  • Controlling Notification Permissions

    Note: Below Step 1 and Step 2 should be done before takeOff()

Prior to initializing the Messenger, you have the option to contol push notifications based on the user's app settings and permission request, provided your app has already obtained permission from the user.

  1. To deactivate the push notifications according to the user’s application setting or if the user has not granted notification permission to your application:

    1. Swift

      SPRMessenger.pushManager().pushEnabled = false // Disable if app settings are disabled

    2. Objective C

      [[SPRMessenger pushManager] setPushEnabled:NO]; // Disable if app settings are disabled

  2. The live chat application will never request notification permission again if it has already been granted. When your application has not obtained notification permissions and if you also wish to prevent the live chat application from requesting notification permission when 'takeOff' is called, you can set the 'autoRequestPermission' parameter to false.

    1. Swift

      SPRMessenger.pushManager().autoRequestNotificationPermissions = false // App will not ask the permission for push notifications

    2. Objective C

      [[SPRMessenger pushManager] setAutoRequestNotificationPermissions:NO]; // App will not ask the permission for push notifications

  3. Whenever the user has granted notification permission to your application, we need to ensure that the push notifications for live chat application are also enabled. To do this:

    1. Swift

      SPRMessenger.pushManager().pushEnabled = true

    2. Objective C

      [[SPRMessenger pushManager] setPushEnabled:YES];

  • Customizing Notification preference 

Note: Please raise a support ticket at tickets@sprinklr.com with the name of the notification sound file you have added to your assets.

Brands have the option to customize sound notifications for Push Notifications. This allows brands to personalize the notification experience by choosing specific sounds that align with their brand identity or user preferences. 

Step 7: In-App Notification 

In-app notifications are messages or alerts displayed within a mobile application itself, rather than on the device's main notification tray or lock screen. These notifications are specifically tailored to communicate information directly to the user while they are actively engaged with the app. 

1) Enable/Disable In-App Notifications 

By default, in-app notifications are enabled. To disable or enable in-app notifications again for Sprinklr Live Chat, please contact Sprinklr Support at tickets@sprinklr.com. Be sure to raise separate support tickets for sandbox and production environments. 

2) Customizing Notification preference 

For in-app notifications, you can provide a custom notification sound or choose to disable the sound entirely. To set this up, please refer to the code below: 

1. Customize Sound for Push Notifications 

Brands have the option to enable a custom sound for their In-App notifications. Please find the relevant code below for reference.. 

Swift 

let notificationPreferences = SPRNotificationPreferences() 
 
if let soundUri = Bundle.main.path(forResource: "notification_sound", ofType: "mp3"), !soundUri.isEmpty { 
    notificationPreferences.soundUri = soundUri 
} 
 
SPRMessenger.pushManager().setNotificationPreference(notificationPreferences)

 Objective C 

SPRNotificationPreferences *notificationPreferences = [SPRNotificationPreferences new]; 
 
NSString *soundUri = [[NSBundle mainBundle] pathForResource:@"notification_sound" ofType:@"mp3"]; 
if (soundUri != nil && soundUri.length > 0) { 
  notificationPreferences.soundUri = soundUri; 
} 
 
SPRMessengerPushManager* sprMessengerPushManager = [SPRMessenger pushManager];[sprMessengerPushManager setNotificationPreference:notificationPreferences]; 

2. Disable Sound 

Brands have the option to disable sound for In-App notifications based on their preferences. Please find the relevant code below for reference.

Swift 

let notificationPreferences = SPRNotificationPreferences() 
 
notificationPreferences.soundDisabled = true // default value is false 
 
SPRMessenger.pushManager().setNotificationPreference(notificationPreferences)

 Objective C 

SPRNotificationPreferences *notificationPreferences = [SPRNotificationPreferences new]; 
 
notificationPreferences.soundDisabled = YES; // default value NO 
 
SPRMessengerPushManager* sprMessengerPushManager = [SPRMessenger pushManager];[sprMessengerPushManager setNotificationPreference:notificationPreferences];

 

Step 8: Taking video calls on messenger 

​Note: Please follow the below Step 7 - Taking video call on messeger if you are using Video Calls

Video call is a feature that allows brands to make video calls on the mobile application. Video calls can be initiated by agents. Sprinklr provides video call solution in integration with 1 vendor as of today i.e. with Zoom.

Pre-Requisites

  1. Zoom account

  2. Permission to access to care console in the Sprinklr platform

Note: You can enable Zoom account to make and receive video calls by reaching out to Sprinklr support at tickets@sprinklr.com

Pricing

  1. Video call solution has a usage-based pricing i.e. per minute per participant costs. Eg- a call between an agent and a customer makes 2 participants

  2. Zoom charges $0.0034 per minute per attendee (one attendee is an agent and the other is a customer)

Note: Step 6 is mandatory for this step 

Install zoom related dependencies 

To start with this,  

  1. Download the SPRMessengerClientZoomVideoSDK zip and podspec file and keep both of them in the same directory.  

  2. Add SPRMessengerClientZoomVideoSDK to your Podfile and run the following code 

    pod install 

    target :YourTargetName do 

    pod 'SPRMessengerClientZoomVideoSDK', :podspec => <path_to_messenger_folder>/SPRMessengerClientZoomVideoSDK.podspec 

    pod 'ZoomVideoSDK/ZoomVideoSDK',  '1.11.0' 

    end

For showing incoming video calls we rely on the iOS provided call kit infrastructure to give an experience of a real call. This also helps the user to control actions like end call, mute call and other call kit actions from both the video call ui as well as the call kit ui. To leverage this, Sprinklr uses voip push notifications which helps users to receive calls on their devices. 

Setup VoIP Push Notifications 

  1. Add PushKit into your app 

    Implement Apple's PushKit API directly into your app to get a VoIP token. See Apple's VoIP Best Practices for more help on getting setup. 

  2. Generate VoIP Certificate 

    The certificate generated must be a VoIP Services Certificate. 
    You must use the same bundle id for the VoIP cert as you do for your main app. Creating voip certificates 

      

  3. Share generated VoIP Certificate in p12 format with Sprinklr along with its password. 


Register/Unregister for voip push notifications 

  1. Register VoIP Token 

    Inside didUpdatePushCredentials, add following code: 

    Swift 

    func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) { 

    SPRMessenger.voipPushManager().didUpdate(pushCredentials, forType: type.rawValue) 

    Objective C

    - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)pushCredentials forType:(PKPushType)type { 

    [[SPRMessenger voipPushManager] didUpdatePushCredentials:pushCredentials forType:(NSString *)type]; 

  2. Unregister voip token 

    Inside didInvalidatePushTokenForType add following code:

    Swift 

    func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) { 

    SPRMessenger.voipPushManager().didInvalidatePushToken(forType: type.rawValue) 

    Objective C 

    - (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type { 

    [[SPRMessenger voipPushManager] didInvalidatePushTokenForType:(NSString *)type]; 

 

Handle VoIP Notifications 

Send VoIP Notification to Messenger SDK if its type belongs to messenger Inside didReceiveIncomingPushWithPayload add following code 

Swift 

func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) { 

if (SPRMessenger.voipPushManager().canHandleVoipPushEvent(payload)) { SPRMessenger.voipPushManager().handleVoipPushEvent(payload, forType: type, 

completion: completion) 

Objective C 

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion { 

 

if ([[SPRMessenger voipPushManager] canHandleVoipPushEvent: payload]) { [[SPRMessenger voipPushManager] handleVoipPushEvent:payload forType:type 

completion:completion]; return; 

             } 

// Add your custom code 

Pass video call provider to SPRMessengerConfig 

Create config for takeOff as done in Step 3 and pass videoCallProvider in the config 

Swift 

import SPRMessengerClient 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 

let config = SPRMessengerConfig(); 

config.appId = "SPR_APP_ID" // This will be provided by sprinklr

config.appKey = "com.sprinklr.messenger.release" // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID

config.deviceId = "UNIQUE_DEVICE_ID"; 

config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg.PROD2) 

config.locale = "SPR_LOCALE"; // default value is en

config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK 

config.videoCallProvider = SPRZoomProvider 

SPRMessenger.takeOff(config) 

Objective C 

#import <SPRMessengerClient/SPRMessenger.h> #import <SPRMessengerClient/SPRMessengerConfig.h> 

#import <SPRMessengerClient/SPRMessengerViewController.h> 

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { 

SPRMessengerConfig *config = [SPRMessengerConfig new];

config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr 

config.appKey = @"com.sprinklr.messenger.release" // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID

config.deviceId = @"UNIQUE_DEVICE_ID"; 

config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2) 

config.locale = @"SPR_LOCALE"; // default value is en

config.themeMode = @"DEFAULT";  // default value is DEFAULT, options: DEFAULT | DARK

config.videoCallProvider = SPRZoomProvider; 

[SPRMessenger takeOff:config]; 

Step 9: Enable SSL Pinning 

Enable SSL Pinning and Public Key provided by sprinklr by creating SPRSSLPinning object and pass it to SPRMessengerConfig

Note: Please raise a support ticket to tickets@sprinklr.com for generating the Public Key 

Swift 

import SPRMessengerClient 
 
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
        let config = SPRMessengerConfig(); 
        config.appId = "SPR_APP_ID" // This will be provided by sprinklr 
        config.appKey = "com.sprinklr.messenger.release"  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.
        config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID
        config.deviceId = "UNIQUE_DEVICE_ID"
        config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2) 
        config.locale = "SPR_LOCALE"; // default value is en 
        config.skin = "MODERN"; // default value is CLASSIC, options: CLASSIC | MODERN

  config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK
 
        let sslPinningConfig = SPRSSLPinningConfig();
        sslPinningConfig.enabled = true
        sslPinningConfig.publicKey = "SPR_PUBLIC_KEY"; // This will be provided by sprinklr 

 
        config.sslPinningConfig = sslPinningConfig; 
 
        SPRMessenger.takeOff(config) 

Objective C

#import <SPRMessengerClient/SPRMessenger.h> 
#import <SPRMessengerClient/SPRMessengerConfig.h> 
#import <SPRMessengerClient/SPRMessengerViewController.h> 
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
 
  SPRMessengerConfig *config = [SPRMessengerConfig new]; 
  config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr 
  config.appKey = @"com.sprinklr.messenger.release" // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.
  config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID 
  config.deviceId = @"UNIQUE_DEVICE_ID"
  config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2) 
  config.locale = @"SPR_LOCALE"; // default value is en 
  config.skin = @"MODERN"; // default value is CLASSIC, options: CLASSIC | MODERN

config.themeMode = @"DEFAULT"// default value is DEFAULT, options: DEFAULT | DARK
 
  SPRSSLPinningConfig *sslPinningConfig = [[SPRSSLPinningConfig alloc] init]; 
  sslPinningConfig.enabled = YES
  sslPinningConfig.publicKey = @"SPR_PUBLIC_KEY"; // This will be provided by sprinklr 
 
  config.sslPinningConfig = sslPinningConfig; 
 
 
  [SPRMessenger takeOff:config]; 

Step 10: Enable Co-Browsing

Co-browsing will allow agents to get full visibility into the customer’s screen, enabling them to guide customers through product purchases, complex form filling, or confusing information on mobile application. For more details, please refer here .

 

Prerequisite

To enable co-browsing, please raise a support ticket at tickets@sprinklr.com with the following details

  • Partner Name

  • Partner ID

  • Concurrent co-browsing sessions expected

  • Number of agents who will be using co-browsing

 

Install Co-Browsing related dependencies

To start with this,

  1. Download the SPRMessengerClientCobrowseSDK zip and podspec file and keep both of them in the same directory.

  2. Add SPRMessengerClientCobrowseSDK to your Podfile and run the following code

    pod install

    target :YourTargetName do

    ​pod 'CobrowseIO/XCFramework', '2.29.6'

    pod 'SPRMessengerClientCobrowseSDK', :podspec => '<path_to_messenger_folder>/SPRMessengerClientCobrowseSDK.podspec'

    end

  3. Create config for takeOff as done in step 3 and Pass Co-browsing Flag as true

    Swift

    import SPRMessengerClient

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let config = SPRMessengerConfig();

    config.appId = "SPR_APP_ID"; // This will be provided bysprinklr

    config.appKey = "com.sprinklr.messenger.release"; // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

    config.pushAppId = "SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID

    config.deviceId = "UNIQUE_DEVICE_ID";

    config.environment = "SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

    config.locale = "SPR_LOCALE"; // default value is en

    config.skin = "MODERN"; // default value is CLASSIC, options: CLASSIC | MODERN
    config.themeMode = "DEFAULT"; //default value is DEFAULT, options: DEFAULT| DARK

    config.isCobrowsingEnabled = true

    SPRMessenger.takeOff(config)

    }

    Objective C

    #import <SPRMessengerClient/SPRMessenger.h>

    #import<SPRMessengerClient/SPRMessengerConfig.h>

    #import <SPRMessengerClient/SPRMessengerViewController.h>

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    SPRMessengerConfig *config = [SPRMessengerConfig new];

    config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr

    config.appKey = @"com.sprinklr.messenger.release"; // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

    config.pushAppId = @"SPR_PUSH_ID"; // Should be Unique id, if not sure pass same as device ID

    config.deviceId = @"UNIQUE_DEVICE_ID";

    config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

    config.locale = @"SPR_LOCALE"; // default value is en
    config.skin = @"MODERN"; // default value is CLASSIC, options: CLASSIC | MODERN

    config.themeMode= @"DEFAULT";  // default value is DEFAULT, options: DEFAULT| DARK

    config.isCobrowsingEnabled = YES;

    [SPRMessenger takeOff:config];

    }

Step 11: Generate User Hash

The userHash is a generated HMAC or Hash-based Message Authentication Code. For HMAC Sprinklr uses the sha256 hash function. You need to generate HMAC for the following "string" of user details. User details are concatenated to form a string, separated by underscore as shown below:

userId_firstName_lastName_profileImageUrl_phoneNo_email

So for the above example, the string for which you need to generate the hash would be

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com

Sample function to generate hash in Swift:

import Foundation
import CommonCrypto


func hmac(message: String, key: String) -> String? {
      guard let signatureData : Data = message.data(using: .utf8), let keyData = key.cString(using:String.Encoding.utf8) else {
            return nil
        }
        var hmacContext = CCHmacContext()
        let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
        CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), keyData, keyData.count)
        CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
        CCHmacFinal(&hmacContext, digest)
        let result = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
        let hexEncodedString = result.map { String(format: "%02hhx", $0) }.joined()
        return hexEncodedString
    }

let hmacResult = hmac(message: "12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com", key: "1f5fb9bd-27a6-4057-823c-94a23be1d2a2");

The secret key which is used in HMAC for your application can be found on the Sprinklr platform as shown below (displayed as API Key):

Note:

  • firstName, hash and one of email or phoneNumber are mandatory

  • User details are supposed to be concatenated to form a string, separated by underscore as shown below:

userId_firstName_lastName_profileImageUrl_phoneNo_email

  •  If you don’t have a few values, you need not send anything but keep the underscores as is. For example, let’s say you don’t have profileimageUrl, there will be 2 underscores after lastName. The string will be as shown below: 

userId_firstName_lastName__phoneNo_email

Objective C

#import <SPRMessengerClient/SPRMessenger.h>

#import <SPRMessengerClient/SPRMessengerConfig.h>

#import <SPRMessengerClient/SPRMessengerViewController.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

SPRMessengerConfig *config = [SPRMessengerConfig new];

config.appId = @"SPR_APP_ID"; // This will be provided by sprinklr

config.appKey = @"com.sprinklr.messenger.release" // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.pushAppId = @"SPR_PUSH_ID"; // unique key

config.deviceId = @"UNIQUE_DEVICE_ID";

config.environment = @"SPR_ENVIRONMENT"; // This will be provided by sprinklr (eg. PROD2)

config.locale = @"SPR_LOCALE"; // default value is en

config.skin = @"MODERN"; // default value is CLASSIC, options: CLASSIC | MODERN

SPRSSLPinningConfig *sslPinningConfig = [[SPRSSLPinningConfig alloc] init];

sslPinningConfig.enabled = YES;

sslPinningConfig.publicKey = @"SPR_PUBLIC_KEY"; // This will be provided by sprinklr

config.sslPinningConfig = sslPinningConfig;

[SPRMessenger takeOff:config];

}

Troubleshoot

1) Add a "View controller-based status bar appearance" and set its value to NO

  • In Info.plist as shown below:

2) If you are unable to load the live chat screen and see an infinite loader or error screen, then check following:

  • From Live chat builder, ensure in whitelisted IPs, you have put  “ * “ for your application 

  • Steps: Modern Care → Live Chat Care → “ three dots” next to your Live chat Application → Edit → Application Configuration Screen 
     

  • Reach out to product team to set the "enforceSecurity" flag to false for your live chat application 

3) LiveChat not showing up while passing authenticated user details 

Check the expected hash for any authenticated user passed inside chat settings. 

  • Hover over the Options icon alongside your Live Chat Application and select Validate User Hash
     

  • On the Validate User Hash window, enter User ID, Profile Image URL, First Name, Last Name, Phone Number and Email. Click Copy Generated Hash and verify it with the hash generated by you.