Get started with the SDK

This article provides steps to include the SDK in your app's code so that the app can initialize the SDK and start using the SDK's features.

📘

Wait. Are you ready for this part?

We hope that you could set up the SDK and get all the files into your Xcode project. If not, then we suggest that you perform the steps to set up the SDK in your project before you start including the SDK in your code.

We'll wait. Take your time. No pressure. :relaxed:

Permissions required

We need the following permissions in your project to send notifications to the end user and collect events from your app:

After adding the Push Notifications capability and enabling Remote notifications background mode, it should look like below.

Initialize the SDK

To get started, include the SDK's header file in the AppDelegate.h or AppDelegate.swift file of the app's Xcode project.

If the programming language is Objective-C, include the SDK's header in AppDelegate.h:

<BlueShift-iOS-SDK/BlueShift.h>    
@interface AppDelegate : UIResponder <UIApplicationDelegate>

If the programming language is Objective-C, add the following code in the AppDelegate.m file. If it's Swift, import the SDK in AppDelegate.swift and add the following code:

import BlueShift_iOS_SDK
class AppDelegate: UIResponder, UIApplicationDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Obtain an instance of BlueShiftConfig
    let config: BlueShiftConfig = BlueShiftConfig()
    
    // Set the api Key for the config
    config.apiKey = "Your API Key here"

    // Set user notification delegate. This delegate will be used while 
   // registering for remote notifications. In case you don't set it up, 
   // SDK will set its own delegate.
    config.userNotificationDelegate = self
  
    // Required from v2.1.7: Set AppGroupId to improve push notification delivery and click tracking
    config.appGroupID = "Your App Group ID here" 

    // v2.1.12 - Set isSceneDelegateConfiguration to true if the app is 
    // using sceneDelegate configuration. By default it is set to false.
    if #available(iOS 13.0, *) {
         config.isSceneDelegateConfiguration = true
    }

    // Optional: Set custom authorization options
    config.customAuthorizationOptions = [.alert, .badge, .sound, .providesAppNotificationSettings]

    // Optional: Set custom categories
    config.customCategories = getCustomeCategories();

    // Optional: Set Batch upload interval in seconds.
    // If you do not add below line, SDK by default sets it to 
    // 300 seconds.
    BlueShiftBatchUploadConfig.sharedInstance().batchUploadTimer = 60;
  
    // Optional: SDK uses IDFV by default if you do not 
    // include the following line of code.For more information,
    // see: https://developer.blueshift.com/docs/include-configure-initialize-the-ios-sdk-in-the-app#specify-the-device-id-source
    config.blueshiftDeviceIdSource = .idfvBundleID
    
    //Optional: Set debug true to see Blueshift SDK info and api logs, by default its set as false.
    config.debug = true;
  
    // Optional: Set the applications launch Options for SDK to track
    config.applicationLaunchOptions = launchOptions

    // Optional: (Deprecated) Set the Three Predefined DeepLinking URL's for 
    // category based push notifications
    config.productPageURL = NSURL.init(string: "Product page URL here") as URL!
    config.cartPageURL = NSURL.init(string: "Cart page URL here") as URL!
    config.offerPageURL = NSURL.init(string: "Offer page URL here") as URL!

    // Initialize the configuration.
    BlueShift.initWithConfiguration(config)
    
    return true
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Obtain an instance of BlueShiftConfig.
 BlueShiftConfig *config = [BlueShiftConfig config];

 // Set the api Key for the config.
 [config setApiKey:@"Your API Key here"];

    // Set user notification delegate. This delegate will be used while registering for remote notifications. In case you don't set it up, SDK will set its own delegate.
 [config setUserNotificationDelegate:self];
 
  // Required from v2.1.7: Set AppGroupId to improve push notification delivery and click tracking
 [config setAppGroupID:@"Your App Group ID here"];

  // v2.1.12 - Set isSceneDelegateConfiguration to true if the app is using sceneDelegate configuration. By default it is set to false.
  [config setIsSceneDelegateConfiguration:YES];

  // Optional: Set custom authorization options
  config.customAuthorizationOptions = UNAuthorizationOptionAlert| UNAuthorizationOptionSound| UNAuthorizationOptionBadge| UNAuthorizationStatusProvisional;

  // Optional: Set custom categories
  config.customCategories = [self getCustomeCategories];
    
 // Optional: Set Batch upload interval in seconds.
 // If you do not add below line, SDK by default sets it to 
 // 300 seconds.
 [[BlueShiftBatchUploadConfig sharedInstance] setBatchUploadTimer:60.0];

  // Optional: SDK uses IDFV by default if you do not 
  //include the following line of code.For more information, see:
  //https://developer.blueshift.com/docs/include-configure-initialize-the-ios-sdk-in-the-app#specify-the-device-id-source
 [config setBlueshiftDeviceIdSource: BlueshiftDeviceIdSourceIDFVBundleID];
  
 //Optional: Set debug true to see Blueshift SDK info and api logs, by default its set as false.
 [config setDebug:YES];
  
 // Optional: Set the applications launch Options for SDK to track.
 [config setApplicationLaunchOptions:launchOptions];

 // Optional: Set the Three Predefined DeepLinking URL's for category based push notifications
 [config setProductPageURL:[NSURL URLWithString:@"Product page URL here"]];
 [config setCartPageURL:[NSURL URLWithString:@"Cart page URL here"]];
 [config setOfferPageURL:[NSURL URLWithString:@"Offer page URL here"]];
  
  // Initialize the configuration
 [BlueShift initWithConfiguration:config];

 return YES;
}

If you look at the code, you can see that we are creating a config class of the type BlueShiftConfig. This is an important class that corresponds to the SDK's configuration. This class specifies the values our SDK requires to work properly. To initialize the SDK successfully, your app should create and pass a valid instance of this class to the SDK.

Required values

The values that are required to configure the SDK are:

  • API key
    The SDK uses the API key to connect to our platform and send data the SDK collects from your app to our platform. This is a mandatory field, and ensure that you generate a key and provide it here. You can get the API key from the API Keys tab in Account page of the Blueshift app. Provide the Event API Key for this setting.
  • userNotificationDelegate -
    The SDK uses this delegate while registering for the remote notifications and iOS gives a callback to the implemented userNotification delegate methods when push notification action/event happens. If you skip setting this delegate, SDK will create its own delegate and use it while registering for remote notifications. All the userNotification push notification action/event will then go to SDK's delegate.
  • appGroupID
    iOS SDK v2.1.7 onwards, you must set appGroupId. It improves the push notification delivery tracking and carousel push notification click tracking.
  • Debug flag
    iOS SDK v2.1.7 onwards you can see the SDK logs. The SDK logs are divided into 4 categories:
    • Errors
    • Exceptions
    • Info
    • Api call info
      Errors and Exceptions are printed by default. To enable info and API call info logs, set config.debug = true during SDK initialization.
  • DeviceIdSource
    SDK sets IDFV as the deviceIdSource by default if you don't set it manually. In case of multiple apps, we recommend setting it to the idfvBundleID option.
  • Launch options
    The SDK uses this option to track if the app is launched from push notification.
  • isSceneDelegateConfiguration
    iOS SDK v2.1.12 onwards, the SDK supports the sceneDelegate enabled single window and multi-window apps. If app is a sceneDelegate enabled app, then set the isSceneDelegateConfiguration variable to true. By default, it is set to false.
  • Deep linking page URLs(Deprecated)
    The SDK uses this option to connect category based push notification campaigns to the pages of your app. The syntax to provide a URL is:
    <scheme>://<scheme_identifier>/<view_controller_identifier_1>/../<view_controller_identifi er_n>.
    Where:
    - <scheme> is ­ the scheme name. This is generally your app's name.
    - <scheme_identifier> is­ the identifier that specifies the scheme ID. Usually, it's the bundle identifier.
    - <view_controller_identifier> is­ the unique storyboard ID that represents the view controller.
    For example:
    blueshiftdemoapp://com.blueshift.demoapp/viewcontroller1/viewcontroller2
    This URL scheme enables deep linking between two view controllers.

📘

Note

The API key is a mandatory value that you need to specify before initializing the SDK. The rest of the methods are optional, so you can use them to customize the SDK and use its features based on your requirements.

Auto-integration

Call + (void) autoIntegration after calling + (void) initWithConfiguration:(BlueShiftConfig *)config for making things simpler. It will set [UIApplication sharedApplication].delegate to an instance of BlueShiftAppDelegate, and it will handle all appDelegate methods. You need not implement any appDelegate methods. But, after after you do this, if your app tries to access [UIApplication sharedApplication].delegate, it will return BlueShiftAppDelegate instead of appDelegate. If you run into issues, integrate your app with Blueshift manually.

If you have opted in for the autoIntegration and you are using sceneDelegate configuration, then you will still need to configure the SDK for the sceneDelegate methods as mentioned below in this article.

// Initialize the configuration
BlueShift.initWithConfiguration(config)
    
// Auto Integration
BlueShift.autoIntegration()
// Initialize the configuration.
 [BlueShift initWithConfiguration:config];
  
// Auto Integration
 [BlueShift autoIntegration];

Configure AppDelegate for push notifications

In addition to configuring push notifications, add the following to the AppDelegate file of your app's Xcode project. Configuring the remoteNotification and userNotificationCenter delegate methods will

  • Share the device token received from the OS with SDK
  • Share the push and silent notification payload to SDK
  • Share the push notification click response to SDK

SDK automatically fires an identify call when it receives a device token for the very first time and when the device token gets changed.

In case if you have integrated push notifications from multiple sources, you can identify if a push notification is sent from Blueshift using the SDK helper method. You can refer to this document for more details.

//configure remote notifications
extension AppDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        BlueShift.sharedInstance()?.appDelegate.register(forRemoteNotification: deviceToken)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        BlueShift.sharedInstance()?.appDelegate.failedToRegisterForRemoteNotificationWithError(error)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
         BlueShift.sharedInstance()?.appDelegate.handleRemoteNotification(userInfo, for: application, fetchCompletionHandler: completionHandler)
    }
}

//configure UserNotificationCenter 
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        BlueShift.sharedInstance()?.userNotificationDelegate.handleUserNotification(center, didReceive: response, withCompletionHandler: completionHandler)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        BlueShift.sharedInstance()?.userNotificationDelegate.handle(center, willPresent: notification, withCompletionHandler: completionHandler)
    }
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken {
    [[BlueShift sharedInstance].appDelegate registerForRemoteNotification:deviceToken];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    [[BlueShift sharedInstance].appDelegate failedToRegisterForRemoteNotificationWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler {
    [[BlueShift sharedInstance].appDelegate handleRemoteNotification:userInfo forApplication:application fetchCompletionHandler:handler];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
    [[BlueShift sharedInstance].appDelegate application:application handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(nonnull UILocalNotification *)notification {
    [[BlueShift sharedInstance].appDelegate application:application handleLocalNotification:notification];
}

- (void)application:(UIApplication *) application handleActionWithIdentifier: (NSString *) identifier forRemoteNotification: (NSDictionary *) notification completionHandler: (void (^)()) completionHandler {  
    [[BlueShift sharedInstance].appDelegate handleActionWithIdentifier:identifier forRemoteNotification:notification completionHandler:completionHandler];
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    [[BlueShift sharedInstance].userNotificationDelegate handleUserNotificationCenter:center willPresentNotification:notification withCompletionHandler:^(UNNotificationPresentationOptions options) {
        completionHandler(options);
    }];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    [[BlueShift sharedInstance].userNotificationDelegate handleUserNotification:center didReceiveNotificationResponse:response withCompletionHandler:^{
        completionHandler();
    }];
}

Batch upload interval

The SDK uses this option to upload the data to our platform either at the specified intervals in batches or in real-time. The SDK uploads the data that it collects on your app. If the device is offline and the app triggers the SDK events, all these events will be batched and sent to the server in batches when the device goes online.

  • Batched events are sent to our platform using the bulk event API. The events are added to a persistent queue which ensures that they are not lost if the user force quits the app. The SDK creates batches of 100 events from the queue based on the time interval that you specify here, and sends them to us from a thread that runs in the background and does not block the app's UI.
  • You can configure the SDK to send events either real-time, or batched using the bulk event API. You may prefer sending certain events (purchases, for example) real-time to us. The SDK stores these events in a queue if no network is available. In this situation, the events are sent as a part of the next batch, as soon as the network is available.
  • The last argument in each method controls whether an event is sent either in real-time, or in a batch. For example, the method to track custom events (in Swift) is: BlueShift.sharedInstance().trackEvent(forEventName: "testing swift", canBatchThisEvent: false). You can see that the last parameter we use is: canBatchThisEvent and it's set to false. In this case, the event is sent to us in real-time.

📘

Note

Make sure you do not set the BlueShiftBatchUploadConfig.sharedInstance()?.batchUploadTimer to 0 seconds. Setting it to 0 seconds will fail to initialize the batch upload queue to recursively send the events to the server.

Configure AppDelegate for batch uploads

To configure the batch uploads, add the following to your project.

Non SceneDelegate app
Add the following code to the AppDelegate class of your app's Xcode project

//Configure app lifecycle events for batch event processing 
extension AppDelegate {
    func applicationDidBecomeActive(_ application: UIApplication) {
        BlueShift.sharedInstance()?.appDelegate.appDidBecomeActive(application)
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
      BlueShift.sharedInstance()?.appDelegate.appDidEnterBackground(application)
    }
}
//Configure app lifecycle events for batch event processing 

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[BlueShift sharedInstance].appDelegate appDidEnterBackground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[BlueShift sharedInstance].appDelegate appDidBecomeActive:application];
}

SceneDelegate enabled app
Add the following code to the SceneDelegate class of your app's Xcode project

//Configure scene lifecycle events for batch event processing
   func sceneWillEnterForeground(_ scene: UIScene) {
        blueshiftAppDelegate?.sceneWillEnterForeground(scene)
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        blueshiftAppDelegate?.sceneDidEnterBackground(scene)
    }
//Configure scene lifecycle events for batch event processing
- (void)sceneWillEnterForeground:(UIScene *)scene API_AVAILABLE(ios(13.0)){
    [[BlueShift sharedInstance].appDelegate sceneWillEnterForeground:scene];
}

- (void)sceneDidEnterBackground:(UIScene *)scene API_AVAILABLE(ios(13.0)){
    [[BlueShift sharedInstance].appDelegate sceneDidEnterBackground:scene];
}

Setting user info

Use the BlueShiftUserInfo class to send the user details to Blueshift. SDK will add values saved in the BlueShiftUserInfo to each event and send it to the Blueshift server. The user-specific details can be saved when the user is logged in to the app.

In order to associate the events to the correct user, there are three primary identifiers used to identify a user uniquely.

  • DeviceID - This will be auto-generated by SDK and sent to the Blueshift server as device_id attribute as part of every event. You can refer to this document to find more on the device Id types supported by the SDK.
  • EmailId - Email id needs to be set to BlueShiftUserInfo.sharedInstance()?.email variable whenever it changes and this will be sent to Blueshift server as part of every event.
  • CustomerId - Customer id needs to be set to BlueShiftUserInfo.sharedInstance()?.retailerCustomerID SDK variable whenever it changes and this will be sent to Blueshift server as part of every event.

Here is an example of how to set customer_id, email, and additional user information after a user signs in:

// On sign in complete
BlueShiftUserInfo.sharedInstance()?.email = "User Email ID"
BlueShiftUserInfo.sharedInstance()?.retailerCustomerID = "User Customer ID"

//Set other user info as below. This info will be used for running
//personalized campaigns 
BlueShiftUserInfo.sharedInstance()?.firstName = "add first name"
BlueShiftUserInfo.sharedInstance()?.lastName = "add last name"
BlueShiftUserInfo.sharedInstance()?.gender = "add gender"
BlueShiftUserInfo.sharedInstance()?.dateOfBirth = "add DOB"

//From SDK v2.1.17, you can set custom user attributes to the extras dictionary
BlueShiftUserInfo.sharedInstance()?.extras = ["userType":"Premium","subExpiryDate":"15-10-2021"]

// It is important to save the information after updating it
BlueShiftUserInfo.sharedInstance()?.save()
// On sign in complete
[[BlueShiftUserInfo sharedInstance] setEmail:@"User Email ID"];
[[BlueShiftUserInfo sharedInstance] setRetailerCustomerID: "User Customer ID"];

//Set other user info as below. This info will be used for running personlised campaigns 
[[BlueShiftUserInfo sharedInstance] setFirstName: @"add first name"];
[[BlueShiftUserInfo sharedInstance] setLastName: @"add last name" ];
[[BlueShiftUserInfo sharedInstance] setGender: @"add gender"];
[[BlueShiftUserInfo sharedInstance] setDateOfBirth: @"add DOB"];

//From SDK v2.1.17, you can set custom user attributes to the extras dictionary
[[BlueShiftUserInfo sharedInstance] setExtras:@{@"userType":@"Premium",@"subExpiryDate":@"15-10-2021"}];

// It is important to save the information after updating it
[[BlueShiftUserInfo sharedUserInfo] save];

On logout, the same user info which was associated with the logged-in user needs to be cleared. you can clear the current user info as below:

BlueShiftUserInfo.removeCurrentUserInfo()
[BlueShiftUserInfo removeCurrentUserInfo];

Register the user with Blueshift

As soon as the user information is saved, run the identifyUser event. The identifyUser event is used to identify the end-user who signed into the app. The primary identifier used to identify a user is device_id that is passed to the Blueshift. The device_id is set during the SDK initialization, and it is automatically sent to Blueshift. In addition to sending the device_id, we recommend that you set the email and customer_id of the user. This ensures that we can still attribute the events to the user and generate recommendations for the user if the device_id resets.

Identify call is responsible to update the data for the user profile on the Blueshift server. Whenever any BlueshiftUserInfo data gets changed, we recommend you to fire an identify call to reflect those changes on the Blueshift server.

//Identify user using email id
BlueShift.sharedInstance().identifyUser(withEmail: "User Email ID", andDetails: nil, canBatchThisEvent: false)

//Identify user with customer id, make sure you have set the retailerCustomerID
//in UserInfo as below before calling identify.
BlueShiftUserInfo.sharedInstance()?.retailerCustomerID = "User Customer ID"
BlueShiftUserInfo.sharedInstance()?.save()
BlueShift.sharedInstance().identifyUser(withDetails:nil, canBatchThisEvent: false)

//Identify user with device id if email and customer id is not present
 BlueShift.sharedInstance().identifyUser(withDetails:nil, canBatchThisEvent: false)

//Identify user with custom details
let details = ["name": "Ross Geller", "profession":"paleontologist"]
BlueShift.sharedInstance().identifyUser(withDetails:details, canBatchThisEvent: false)
//Identify user using email id
[[BlueShift sharedInstance] identifyUserWithEmail:@"User Email ID" andDetails:nil canBatchThisEvent:NO];

//Identify user with customer id, make sure you have set the retailerCustomerID in UserInfo as below before calling identify.
[[BlueShiftUserInfo sharedInstance] setRetailerCustomerID: "User Customer ID"];
[[BlueShiftUserInfo sharedInstance] save];
[[BlueShift sharedInstance] identifyUserWithDetails:nil canBatchThisEvent:NO];

//Identify user with device id if email and customer id is not present
[[BlueShift sharedInstance] identifyUserWithDetails:nil canBatchThisEvent:NO];

//Identify user with custom details
NSDictionary *details = @{  @"name":@"Ross Geller",
                            @"profession":@"paleontologist" }
[[BlueShift sharedInstance] identifyUserWithDetails:details canBatchThisEvent:NO];

Deep links on iOS

The Blueshift iOS SDK supports deep links on push notifications and in-app messages. If a deep-link URL is present in the push or in-app message payload, the Blueshift SDK triggers AppDelegate application:openURL:options: on notification click/tap action and delivers the deep link there.
The host app will need to write some business logic in order to process the delivered deep link and navigate to the respective screen inside the app.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
     // Handle deep link url
    return true;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    // Handle deep link url
  return YES;
}

Advanced configurations

Set custom push notification authorization options and notification categories

From SDK v2.2.0 onwards, you can use the 'config' object in the SDK to set custom push notification authorization options and notification categories, which the SDK will use while registering for the remote notifications. You can set them during SDK initialization.

Set custom authorization options

Set your custom authorization options to the customAuthorizationOptions property of the config object during SDK initialization. The given options will be used while registering for the remote notifications.
If you do not set this property during SDK initialization, then SDK will use the default options. The default authorization options used by the SDK are alert, badge, and sound. You can set custom authorization options as follows:

//Set custom authorization options
config.customAuthorizationOptions = [.alert, .badge, .sound, .providesAppNotificationSettings]
//Set custom authorization options
config.customAuthorizationOptions = UNAuthorizationOptionAlert| UNAuthorizationOptionSound| UNAuthorizationOptionBadge| UNAuthorizationStatusProvisional;

Set custom notification categories

Set your custom notification categories to the customCategories property of the config object during SDK initialization. The given categories will be merged with the SDK's custom categories and they will be set to the UNUserNotificationCenter while registering for the remote notifications.
The customCategories property accepts Set of UNNotificationCategory objects. You can set the custom categories as follows. The function getCustomeCategories() returns a set of UNNotificationCategory objects.

//Set custom categories 
//The method getCustomeCategories() should return set 
config.customCategories = getCustomeCategories();
//Set custom categories 
config.customCategories = [self getCustomeCategories];

SDK push notification callbacks

The SDK provides callbacks for these events:

  • When a user taps on the push notifications
  • When a user taps on the action buttons on push notifications

You can write these callbacks in the AppDelegate class by implementing the BlueShiftPushDelegate protocol on the AppDelegate and set the blueShiftPushDelegate as self, but if you want to implement callbacks in a separate class, then your app must pass the custom class reference in the BlueShiftConfig class when the app initializes the SDK.

To pass the custom class reference, create a class that implements the BlueShiftPushDelegate protocol. For example, create BlueshiftPushNotificationEvents class to receive the callbacks of push notifications.

You can find here more about the push notification callback methods.

// BlueshiftPushNotificationEvents is the class for handling 
// BlueShiftPushDelegate delegate methods
let blueshiftPushDelegate = BlueshiftPushNotificationEvents()
config.blueShiftPushDelegate = blueshiftPushDelegate
// BlueshiftPushNotificationEvents is the class for handling BlueShiftPushDelegate delegate methods
 BlueshiftPushNotificationEvents *blueshiftPushDelegate = [[BlueshiftPushNotificationEvents alloc] init];
 [config setBlueShiftPushDelegate:blueshiftPushDelegate];

📘

Note

To avoid duplicate deep-link triggers, don't use deep-links in the push notification callbacks from push notification clicks.

Disable IDFA collection

You can opt-out from the automatic IDFA collection done by the SDK when IDFA permission is available to the host app. Set config.enableIDFACollection to false in order to completely stop collecting the IDFA.
If you would like us to track IDFA when the host app has permission, set the flag to true.
Blueshift SDK does not ask the user for device IDFA collection permission, host app needs to take care of this in order for SDK to track it.

//Disable the idfa collection by the SDK
config.enableIDFACollection = false
//Disable the idfa collection by the SDK
[config setEnableIDFACollection:NO];

📘

Important

From iOS SDK v2.1.17, SDK will not track the IDFA automatically. The host application needs to set the IDFA value to the Blueshift SDK in order to track the IDFA. It is the host app's responsibility to ask IDFA tracking permission and set the value to SDK. We recommend setting the IDFA value immediately after the app launch.

You can set the IDFA to SDK as below.

// Set the IDFA value to SDK if user has accepted the tracking permission
BlueShiftDeviceData.current()?.deviceIDFA = ASIdentifierManager.shared().advertisingIdentifier.uuidString
// Set the IDFA value to SDK if user has accepted the tracking permission
[[BlueShiftDeviceData currentDeviceData] setDeviceIDFA:[ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString];

Delay Push Notification Permission

If you don't want the push notification permission to be displayed on the app launch, you can customize it to display it later after sign up/sign in. To do that you need to set the config.enablePushNotification as false while initializing the SDK.

//Disable push notifications in the SDK configuration in appDelegate to 
//delay the Push notification permission
config.enablePushNotification = false
//Disable push notifications in the SDK configuration in appDelegate to delay the Push notification permission
[config setEnablePushNotification:NO];

Now, you need to enable the push notifications and call the registration for remote notification where you want to display the Push notification permission dialog.

//Enable the push and call registerForNotification to show Push permission
BlueShift.sharedInstance()?.config.enablePushNotification = true
BlueShift.sharedInstance()?.appDelegate.registerForNotification()
//Enable the push and call registerForNotification to show Push permission
[[[BlueShift sharedInstance]config] setEnablePushNotification: YES];
[[BlueShift sharedInstance].appDelegate registerForNotification];

Opt-out of silent push notification registration

SDK registers for silent push notifications by default in order to send in-app notifications when push permission is not asked the user or push permission is not accepted by the user.
From SDK v2.1.13, you can opt-out from silent push notification registration by setting config.enableSilentPushNotification to false.

// Stop SDK from registering for silent(background) push notifications
config.enableSilentPushNotification = false
// Stop SDK from registering for silent(background) push notifications
[config setEnableSilentPushNotification:NO];

Specify the device ID source

If you are using iOS SDK version 2.1.3 or later, You can use either IDFV, UUID, or IDFVBundleID. By default, the SDK picks IDFV if you do not use the following method. However, you can customize the SDK so that it picks UUID or IDFVBundleID instead. In case you have multiple apps, we recommend setting it to IDFVBundleID option.

❗️

If you are an existing Blueshift client, and have not touched this part yet, we want you to exercise caution if you choose a new device ID source. If you have anonymous users (users who use your app without signing in), choosing a new device ID source will delete all the data that we collect.

Use the following method to specify the device ID source you want the SDK to pick.

// Optional: SDK uses IDFV by default if you do not include the following line of code.
config.blueshiftDeviceIdSource = .idfvBundleID
 /*
  * IDFV: Apple Identifier for vendor.
  *
  * idfvBundleID: combination of IDFV and Bundle ID. 
  *
  * UUID: Randomly generated Unique id.
  *
  */
// Optional: SDK uses BlueshiftDeviceIdSourceIDFV by default if you do not include the following line of code.
[config setBlueshiftDeviceIdSource: BlueshiftDeviceIdSourceIDFVBundleID];
 /*
  *BlueshiftDeviceIdSourceIDFV: Apple Identifier for vendor.
  *
  * BlueshiftDeviceIdSourceIDFVBundleID: combination of IDFV and Bundle ID. 
  *
  *BlueshiftDeviceIdSourceUUID: Randomly generated Unique id.
  *
  */

Custom Device ID
If the above device id sources don't meet the requirements, from SDK version 2.1.6 and higher, Blueshift iOS SDK can accept a custom device ID from the host app. This let's you reuse the device_id in use.

To set your own device ID, choose the blueshiftDeviceIdSource as custom and then set the customDeviceId value. Please make sure you set a valid device id. It should not be empty or null and should not contain spaces/special characters.

//Set deviceIDSource as custom
 config.blueshiftDeviceIdSource = .custom
 //Set the custom device id value
 config.customDeviceId = "SET CUSTOM DEVICE ID HERE"
//Set deviceIDSource as custom
 [config setBlueshiftDeviceIdSource: BlueshiftDeviceIdSourceCustom];
 //Set the custom device id value
 [config setCustomDeviceId:@"SET CUSTOM DEVICE ID HERE"];

Location tracking

The location tracking flag enableLocationAccess is set to true by default. To disable location tracking, set config.enableLocationAccess to false during the SDK initialization.

config.enableLocationAccess = false
[config setEnableLocationAccess:NO];

From iOS SDK v2.1.7, SDK will not track the user location automatically. The host application needs to set the updated location to the Blueshift SDK in order to track the user location. It is the host app's responsibility to ask location permission and update the latest location to SDK.

//Set updated location to SDK to track the location
BlueShiftDeviceData.current()?.currentLocation = currentLocation
//Set updated location to SDK to track the location
[[BlueShiftDeviceData currentDeviceData] setCurrentLocation: currentLocation]

Refer this code from our sample application for more details.

Messaging opt-out

Opt out of push messages

From iOS SDK v2.1.8, you can use Blueshift app preferences to opt out of push notifications that we send from our platform. You can use this functionality if you don't want push notifications from our platform to show up on your app.

BlueShiftAppData.current()?.enablePush = false
[[BlueShiftAppData currentAppData]setEnablePush:NO];

Opt out of in-app messages

From iOS SDK v2.1.17, you can use Blueshift app preferences to opt-out of in-app notifications that we send from our platform. You can use this functionality if you don't want in-app messages from our platform to show up on your app.

BlueShiftAppData.current()?.enableInApp = false
[[BlueShiftAppData currentAppData]setEnableInApp:NO];

📘

Ensure that you trigger an identify event so that we don't send push/in-app notifications to the customer that you specify.

In order to start receiving the push or in-app notifications, make sure you re-enable the enablePush/ enableInApp flag and fire identify call.

Point out Blueshift's Push Notifications

From iOS SDK v2.1.8, If you send push notifications to your customers in addition to the ones from the Blueshift platform, you can use the isBlueshiftPushNotification helper methods to point out which push notifications come from our platform:

BlueShift.sharedInstance()?.isBlueshiftPushNotification(userInfo)

BlueShift.sharedInstance()?.isBlueshiftPushNotification(notification.request.content.userInfo)

BlueShift.sharedInstance()?.isBlueshiftPushNotification(response.notification.request.content.userInfo)
[[BlueShift sharedInstance] isBlueshiftPushNotification: userInfo];

[[BlueShift sharedInstance] isBlueshiftPushNotification:notification.request.content.userInfo];

[[BlueShift sharedInstance] isBlueshiftPushNotification: response.notification.request.content.userInfo];

Refer this code from our sample application for more details.

Identify Blueshift push and in-app deep links

SDK v2.1.12 onwards, the options dictionary of the OpenURL method shares additional details about the deep link. The details are in the form of a key-value pair dictionary.
Below is the sample dictionary format that you can expect for push and in-app deep links.

Push notifications
["source": "Blueshift", "channel": "push"]

In-App notifications
["source": "Blueshift", "channel": "inApp", "inAppNotificationType": "modal", "clickedButtonText": "Sure", "clickedButtonIndex": "btn_0"]

The clickedButtonText and clickedButtonIndex are only applicable to modal in-apps.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        // Check if deep link url is from Blueshift.
        if let source = options[UIApplication.OpenURLOptionsKey(rawValue: "source")] as? String, source == "Blueshift" {
            showProductDetail(animated: true, url: url)
        }
        return true
    }
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
   // v2.1.12 - Check if deep link url is from Blueshift.
    if([options[@"source"]  isEqual: @"Blueshift"]) {
        [self showProductDetail:url];
    }
    return YES;
}

Disable SDK tracking

SDK tracks the custom events, push metrics, and in-app metrics by default. From SDK v2.1.14, you can stop SDK from tracking these events based on your use-case.
Disabling the SDK will stop sending custom events and metrics for push and in-app to Blueshift’s server. It will also remove any pending events (batched or real-time) that are yet to be sent to the server.

/// Disable SDK events tracking
BlueShift.sharedInstance()?.enableTracking(false)

To start the SDK events tracking once again after disabling it, you will need to enable it explicitly by calling
BlueShift.sharedInstance()?.enableTracking(true).

Summary

  • The SDK is configured to send identify calls.
  • The SDK is ready to receive the Push notifications from the Blueshift Dashboard.

Test the SDK integration

These are some of the guidelines to verify the correctness of the SDK integration. The most important thing is to ensure that the app is working as it was before integrating with the SDK.

  • SDK is initialized correctly
    Ensure that you do not delay the SDK initialization as it may impact push click tracking. Make sure certain events are launched correctly from the app, such as identify or app_open. You can confirm that the events show up correctly in the activity of a user on the Blueshift dashboard.

  • Push Notifications
    Use the push studio editor to create different types of push messages and ensure that the notifications render correctly on devices. This push configuration will enable the basic title + content notifications. To configure the Rich push notifications, see this.

  • Campaigns
    Create a test campaign for push notifications with the test devices and run it against them to ensure that you are getting click stats. To get the delivered stats, you will need to set up the SDK for the notification service extension. Refer this document for more.

That's it! You are all set to start using the SDK!


What’s Next

Now that you're familiar with our SDK, you can start tracking events on your app. For more information, see:

Did this page help you?