iOS
CustomerGlu SDK for iOS enables you to open CustomerGlu campaigns in your app, add Dynamic Entry Points for the campaigns, Paint rich In-app Nudges, Send user events and a lot more...

Pre-Requisites

CustomerGlu iOS SDK supports IOS 11.0+ and requires Xcode 12 or above to build.

Installation

Option 1: Using CocoaPods

Add CustomerGlu to your Podfile and run pod install
pod 'CustomerGlu'

Option 2: Using Swift Package Manager

Add https://github.com/customerglu/CG-iOS-SDK as a Swift Package Repository in Xcode and follow the instructions to add Intercom as a Swift Package.

Update Info.plist

Set up the following keys in the Info.plist file. This will allow your application to make HTTP requests.
1
<key>NSAppTransportSecurity</key>
2
<dict>
3
<key>NSAllowsArbitraryLoads</key>
4
<true/>
5
</dict>
Copied!

Initialise SDK

⚠
WriteKey - Mandatory (WriteKey/API Key is provided by CustomerGlu)
Add the following key to the Info.plist file.
1
<key>CUSTOMERGLU_WRITE_KEY</key>
2
<string>YOUR_WRITE_KEY</string>
Copied!
​
Define the global instance of CustomerGlu SDK
You can store the global instance of CustomerGlu SDK in a variable so you don't have to use CustomerGlu.getInstance for each function call
1
let customerGlu = CustomerGlu.getInstance
Copied!

Register User (Mandatory)

Use the given function to register a user with CustomerGlu:
1
customerGlu.registerDevice(userdata: userData, loadcampaigns: true) { success, registrationModel in
2
if success {
3
print("Register Successfully \(String(describing: registrationModel))")
4
} else {
5
print("error")
6
}
7
}
Copied!
πŸ’‘Note: The Register function is also used to update the user attributes

Function Parameters:

  1. 1.
    userData: A Dictionary that holds user information
1
var userData = [String: AnyHashable]()
2
userData["userId"] = "testUser_1" // Mandatory:any identifier to uniquely identify a user of your platform
3
userData["userName"] = "John Doe"
4
userData["firebaseToken"] = CustomerGlu.getInstance.fcmToken // for enabling Firebase Notifications
5
userData["apnsDeviceToken"] = CustomerGlu.getInstance.apnToken // for enabling APNS Notifications
6
var customAttributes = [String: AnyHashable]()
7
// any custom key-value pairs, which may be used for targeting can be sent as customAttributes
8
// segments can be created by applying filters on these customAttributes
9
// campaigns can be launched on specific segments
10
customAttributes["orderCount"] = 5
11
customAttributes["city"] = "Mumbai"
12
userData["customAttributes"] = customAttributes
13
var profile = [String: AnyHashable]()
14
profile["firstName"] = "jane"
15
userData["profile"] = profile
Copied!
After put data in user data you can pass them in registerDevice function as show above.
πŸ’‘Note: You can check out the complete userData object payload here​
2. loadcampaigns (Boolean) - It accepts a boolean value- if "true", then a loadCampaigns call is made during registration, ensuring the latest campaigns, the user is eligible for, are pre-fetched (improves load times).

Clear Data on Logout (Mandatory)

Use the given function when the user logs out, to clear CustomerGlu SDK cached data like user_id, token etc.
1
customerglu.clearGluData();
Copied!

Handle Webview Events

Enable Closing of Webview on UI button click
This function will enable closing the CustomerGlu webviews on clicking the close button on the UI:
1
customerGlu.closeWebviewOnDeeplinkEvent(close: true);
Copied!
Enable Analytics Event
If click analytics are to be captured directly via the app, you can enable the analytics events by using the given function:
1
customerglu.enableAnalyticsEvent(event: true)
Copied!
Handling WebEvents
For handling Deeplink events triggered by the webview, you need to add a notification observer:
1
NotificationCenter.default.addObserver(
2
self,
3
selector: #selector(self.catchDeeplinkNotification),
4
name: Notification.Name("CUSTOMERGLU_DEEPLINK_EVENT"),
5
object: nil)
6
​
7
@objc private func catchDeeplinkNotification(notification: NSNotification) {
8
//do stuff using the userInfo property of the notification object
9
if let userInfo = notification.userInfo as? [String: Any] // or use if you know the type [AnyHashable : Any]
10
{
11
print(userInfo)
12
}
13
}
Copied!

Handle Analytics Event

For handling analytics events triggered by the webview, you need to a notification observer:
1
NotificationCenter.default.addObserver(
2
self,
3
selector: #selector(self.catchAnalyticsNotification),
4
name: Notification.Name("CUSTOMERGLU_ANALYTICS_EVENT"),
5
object: nil)
6
@objc private func catchAnalyticsNotification(notification: NSNotification) {
7
if let userInfo = notification.userInfo as? [String: Any]
8
{
9
print(userInfo)
10
}
11
}
Copied!

Functionalities

OpenWallet

Use the given function to open the wallet screen powered by CustomerGlu:
1
customerglu.openWallet()
Copied!

​

LoadCampaignById

Use this function to directly open a specific campaign, if the campaignId/tag is known:
1
customerglu.loadCampaignById(campaign_id: "CAMPAIGN_ID/TAG")
Copied!
  1. 1.
    CampaignId : Unique Identifier assigned to each campaign by default, can be copied from the dashboard.
2. Tag: An optional tag can be assigned to each campaign from the dashboard
​
πŸ’‘
Note: If the value of campaignId/tag provided is empty/invalid, wallet will be opened by default

Entry Points

The following entry points are supported by CustomerGlu SDK:
  • Banners
​
  • Floating Buttons/Launchers
​
  • Popups
​

​

Enable Entry Points

Use the given function to enable Entry Points in the app (needs to be called on every app launch):
1
CustomerGlu.getInstance.enableEntryPoints(enabled: true)
Copied!

Enable SDK Debugging Mode

Debugging mode enables logging and passes the app screen names to CustomerGlu so the list of all available screens of the app is available already on the entry point configuration sections on the dashboard.
After enabling the debugging mode make sure setCurrentClassName() is called in every ViewController’s viewWillAppear() method. After setting up the aforementioned code, run the app on simulator / real-device and navigate to the every screen of the Application.
​
⚠
Please make sure to disable debugging mode in Release/Production build.
​
The given function can be used to enable SDK debugging mode:
1
CustomerGlu.getInstance.gluSDKDebuggingMode(enabled: true)
Copied!

Setting up Banners

​
⚠
Please make sure the component is added to all the possible places where banners might be needed, as an app release will be required to change the same. The banners will only appear when configured on the dashboard to be visible.
Banners can be set up in the given ways:

1. Storyboard / XIB

Drag and drop an empty UIView on the ViewController in which a banner might need to be shown, and adjust it to the correct position. Now, under identity inspector add BannerView as the class name and under attribute inspector add a value for BannerId. You can add height constraint in the same view.

2. SwiftUI

If the app screens are developed using SwiftUI, then add the following banner component, wherever a banner might be needed:
1
// Add code where a banner might be needed
2
Spacer()
3
VStack {
4
AddBannerView()
5
}.padding(.horizontal, 10)
6
Spacer()
7
​
8
//Struct for adding banner view
9
struct AddBannerView: UIViewRepresentable {
10
func updateUIView(_ uiView: BannerView, context: Context) {
11
​
12
}
13
14
func makeUIView(context: Context) -> BannerView {
15
let view = BannerView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width-30, height: 0), bannerId: "Add bannerId ID here")
16
view.setContentHuggingPriority(.required, for: .horizontal)
17
view.setContentHuggingPriority(.required, for: .vertical)
18
return view
19
}
20
}
Copied!
​
πŸ’‘
Note : The bannerId is mandatory and the exact same id needs to be configured on the dashboard as the bannerId in the entry point configuration section. Please follow a semantic nomenclature like screenName_banner_1 for the ids for ease of configuration on the dashboard.
Banner Loaded Callback (optional)
The banner component will be hidden automatically in cases like the banner being disabled, user not eligible to see the banner (not in segment/campaign already completed). If the status of banner components is also needed by the app, the following method can be used to check the banner content by registering a broadcast receiver:
1
// Add Observer to listen Notification with name CUSTOMERGLU_BANNER_LOADED
2
NotificationCenter.default.addObserver(
3
self,
4
selector: #selector(self.getBannersCount),
5
name: Notification.Name("CUSTOMERGLU_BANNER_LOADED"),
6
object: nil)
7
8
// Method to listen notification with name CUSTOMERGLU_BANNER_LOADED
9
@objc private func getBannersCount(notification: NSNotification) {
10
if let userInfo = notification.userInfo as? [String: Any]
11
{
12
// Output - ["banner1":2,"banner2":0]
13
// Key is the bannerId and value is number of banners in the Banner Component
14
print(userInfo)
15
}
16
}
Copied!

Setting up Floating Buttons and Popups

The given function should be used on each ViewController's viewWillAppear() method to support adding the floating button/popup entry points via the dashboard:
1
override func viewWillAppear(_ animated: Bool) {
2
super.viewDidLoad()
3
CustomerGlu.getInstance.setCurrentClassName(className: String(describing: type(of: self)))
4
}
Copied!

Handle CustomerGlu Notifications

To handle the notifications configured via CustomerGlu Dashboard (Push/In-app), use the given method:
Configure Notification Type -
1
customerGlu.isFcmApn(fcmApn:"fcm") //or "apn"
Copied!
Function Parameter:
fcmApn- It accepts string "fcm" or "apn" depending on the notfication service being used by the app.
Set FCM/APNS Token -
Add following code in didFinishLaunchingWithOptions()
1
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
2
​
3
4
UNUserNotificationCenter.current().delegate = self
5
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
6
UNUserNotificationCenter.current().requestAuthorization(
7
options: authOptions,
8
completionHandler: {_, _ in })
9
application.registerForRemoteNotifications()
10
​
11
//Only For FCM
12
FirebaseApp.configure()
13
Messaging.messaging().delegate = self
14
​
15
return true
16
}
17
​
Copied!
Add the following extension in AppDelegate:
1
extension AppDelegate: UNUserNotificationCenterDelegate {
2
3
// Receive displayed notifications for iOS 10 devices.
4
func userNotificationCenter(_ center: UNUserNotificationCenter,
5
willPresent notification: UNNotification,
6
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
7
// Change this to your preferred presentation option
8
CustomerGlu.getInstance.cgUserNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)
9
}
10
11
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //apn
12
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
13
print("Device token: \(tokenString)")
14
CustomerGlu.getInstance.apnToken = tokenString
15
16
// Not required for FCM
17
let userData = [String: AnyHashable]()
18
CustomerGlu.getInstance.updateProfile(userdata: userData) { success, _ in
19
if success {
20
} else {
21
}
22
}
23
24
//Only required for FCM
25
Messaging.messaging().apnsToken = deviceToken
26
print("APNs token retrieved: \(deviceToken)")
27
}
28
29
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
30
}
31
32
func userNotificationCenter(_ center: UNUserNotificationCenter,
33
didReceive response: UNNotificationResponse,
34
withCompletionHandler completionHandler: @escaping () -> Void) {
35
let userInfo = response.notification.request.content.userInfo
36
print(userInfo)
37
CustomerGlu.getInstance.displayBackgroundNotification(remoteMessage: userInfo as? [String: AnyHashable] ?? ["glu_message_type": "glu"])
38
completionHandler()
39
}
40
41
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
42
print(userInfo)
43
CustomerGlu.getInstance.cgapplication(application, didReceiveRemoteNotification: userInfo, backgroundAlpha: 0.5, fetchCompletionHandler: completionHandler)
44
}
45
46
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
47
print(fcmToken)
48
}
49
}
50
​
51
// MARK: FCM Notification delegate
52
extension AppDelegate: MessagingDelegate {
53
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
54
print("Firebase registration token: \(String(describing: fcmToken))")
55
CustomerGlu.getInstance.fcmToken = fcmToken ?? ""
56
let userData = [String: AnyHashable]()
57
CustomerGlu.getInstance.updateProfile(userdata: userData) { success, _ in
58
if success {
59
} else {
60
}
61
}
62
}
63
}
Copied!

Supported Layouts:

  1. 1.
    full-default
​
2. middle-default
​
3. bottom-default
​
4. bottom-slider (the screen can be minimized by dragging it down)
​

​

Send Events

This function can be used to directly send the events to the CustomerGlu :
​
πŸ’‘
Note: Check out all available options to send events here​
1
customerGlu.sendEventData(eventName:"Order_Placed",eventProperties:["orderValue",1000])
Copied!
Function Parameters:
  1. 1.
    eventName: Event names like order_placed, add_to_cart etc.
  2. 2.
    eventProperties - Event properties like orderId, orderAmountetc as a dictonary.

Handle Firebase Deeplinks for Referrals

If Firebase DynamicLinks are being used for referrals, the given function can be used to extract the referrer's userId. The referrer's userId can then be passed while registering the referred user (only valid for the first registration) as the referredBy property as seen here.
1
referID = customerGlu.getReferralId(deepLink);
Copied!

Configure Loader Color

This function can be used to change the color of the loader which appears on the webview window while the webpage is being loaded.
​
πŸ’‘
Note: Default color is Black
1
customerGlu.configureLoaderColour(color: [UIColor.red])
Copied!
Function Parameter:
color - It accepts array of UIColor
​

Configure Safe area

This function can be used to configure the height and color of Top and Bottom safe areas:
1
customerGlu.configureSafeArea(topHeight: 44, bottomHeight: 34,
2
topSafeAreaColor: UIColor.white, bottomSafeAreaColor: UIColor.white)
Copied!

Disable CustomerGlu SDK

All the functions of SDK can be disabled by using the method:
1
customerGlu.disableGluSdk(true);
Copied!
​
Last modified 13d ago