iOS - v9.1.0
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> |
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
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.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
|
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
Swift
import SPRMessengerClient
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.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 let user = SPRMessengerUser(); |
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.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.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.customUser = ["customAttribute1": "value1", "customAttribute2": "value2", "hash": "8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"] // Add your custom attributes
SPRMessenger.takeOff(config); |
Objective C
SPRMessengerConfig *config = [[SPRMessengerConfig alloc] init]; 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.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
Swift
let viewController = SPRMessengerViewController.init(launchOptions: launchOptions);
viewController.modalPresentationStyle = .fullScreen
self.present(viewController, animated: true, completion: nil)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(); |
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"} |
3) Update Language
To update the user language use below function:
Swift
SPRMessenger.shared().updateLocale(locale)
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
Swift
SPRMessenger.shared().logout()
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:
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:
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,
Create the case custom fields and note down their field name
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.
Swift
let conversationContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];
let chatInitialisationContext = ["conversationContext": conversationContext] as [String : Any]
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,
Create the case custom fields and note down their field name
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.
Swift
let clientContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];
config.clientContext = clientContextObjective C
NSDictionary *clientContext = @{
@"5ea7fa9e87651f356209878f": @[@"laptop"],
@"5eb7fa9e87651f356219348e": @[@"inquiry"]
};
config.clientContext = clientContext;
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.
Swift
let clientContext = ["5ea7fa9e87651f356209878f": ["laptop"], "5eb7fa9e87651f356219348e": ["inquiry"]];
SPRMessenger.shared().updateClientContext(clientContext)
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.
Create the case custom fields and note down their field name
All the field values should be passed as an array of strings.
Swift
let conversationContext = ["context": ["5ea7fa9e87651f356209878f": ["laptop"],"5eb7fa9e87651f356219348e": ["inquiry"]]];
SPRMessenger.shared().updateConversationContext(conversationContext)
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,
Create the profile custom fields and note down their field name.
Whenever you want to update the profile custom field, call the following and pass the information for profile level custom fields
Swift
let userContext = ["5ea7fa9e87651f356209878f":
["laptop"],"5eb7fa9e87651f356219348e": ["inquiry"]];
SPRMessenger.shared().updateUserContext(userContext)
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.
Swift
SPRMessenger.shared().close()
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.
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 = selfAnd finally add function to listen to external events payload:
func handleExternalAction(_ payload: [AnyHashable : Any]) {}
Objective C
At top of the class add:
@interface ClassName () <SPRMessengerDelegate>
@endInside 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,
Call the the below function to get the number of open conversations
Swift
SPRMessenger.shared().getNumberOfOpenConversations()
Objective C
[[SPRMessenger shared] getNumberOfOpenConversations];
Add Delegate to listen to the output of above function
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 = selfAnd finally add function to listen to external events payload:
func onUpdateNumberOfOpenConversations(_ count: NSNumber) {}
Objective C
At top of the class add:
@interface ClassName () <SPRMessengerDelegate>
@endInside 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:
Add Delegate to listen to the updates in unread messages count
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 = selfAnd 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
}
}
}
Objective C
At top of the class add:
@interface ClassName () <SPRMessengerDelegate>
@endInside 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
}
}
You can also trigger the event to get the current unread messages count by calling following method:
Swift
SPRMessenger.shared().getUnreadMessagesCount ()
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() |
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> |
Inside the initialisation function of the class add after takeoff:
SPRMessenger* sprMessenger = [SPRMessenger shared]; |
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:
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() |
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> |
Inside the initialisation function of the class add after takeoff:
SPRMessenger* sprMessenger = [SPRMessenger shared]; |
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]) { } |
Objective C
Add logger transport where you have defined your take off method:
@interface ClassName () @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 } |
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(); |
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
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 = [ “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:
Link your custom font files in your iOS project natively, such that the fonts are available throughout the project. For steps, see iOS documentation.
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
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:
APNS certificate (P12) along with its credentials
Live Chat AppID
Partner ID
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:
Swift
SPRMessenger.pushManager().setRegistrationToken(token)
Objective C
[[SPRMessenger pushManager] setRegistrationToken: token];
You can unregister for messenger push notifications by sending empty token as below:
Swift
SPRMessenger.pushManager().setRegistrationToken("")
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:
Swift
let isMessengerNotification = SPRMessenger.pushManager().canHandlePushEvent(userInfo)
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.
Swift
SPRMessenger.pushManager().handlePushEvent(userInfo)
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.
To deactivate the push notifications according to the user’s application setting or if the user has not granted notification permission to your application:
Swift
SPRMessenger.pushManager().pushEnabled = false // Disable if app settings are disabled
Objective C
[[SPRMessenger pushManager] setPushEnabled:NO]; // Disable if app settings are disabled
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.
Swift
SPRMessenger.pushManager().autoRequestNotificationPermissions = false // App will not ask the permission for push notifications
Objective C
[[SPRMessenger pushManager] setAutoRequestNotificationPermissions:NO]; // App will not ask the permission for push notifications
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:
Swift
SPRMessenger.pushManager().pushEnabled = true
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() |
Objective C
SPRNotificationPreferences *notificationPreferences = [SPRNotificationPreferences new]; |
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() |
Objective C
SPRNotificationPreferences *notificationPreferences = [SPRNotificationPreferences new]; |
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
Zoom account
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
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
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,
Download the SPRMessengerClientZoomVideoSDK zip and podspec file and keep both of them in the same directory.
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
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.
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
Share generated VoIP Certificate in p12 format with Sprinklr along with its password.
Register/Unregister for voip push notifications
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];
}
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 config.themeMode = "DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK |
Objective C
#import <SPRMessengerClient/SPRMessenger.h> config.themeMode = @"DEFAULT"; // default value is DEFAULT, options: DEFAULT | DARK |
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,
Download the SPRMessengerClientCobrowseSDK zip and podspec file and keep both of them in the same directory.
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
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 | MODERNconfig.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
|
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.