iOS SDK

Detailed technical documentation on the Lemnisk iOS SDK to send data from your iOS apps to your destinations via Lemnisk.

This document acts as a reference for the iOS SDK documentation. Please ensure that you have an agreed-upon Event Tracking Plan from your Lemnisk Customer Success Point of Contact in conjunction with this document for the correct and complete implementation.

What is the iOS SDK?

The Lemnisk iOS SDK allows you to track user event data from your iOS app. The SDK can be easily imported into any iOS app. Based on the data it receives from the user activity, it sends real-time personalized push notifications to the users about the services and products that our clients provide

Installing and using the Lemnisk iOS SDK

Prerequisites

  • Lemnisk Account Id

  • Lemnisk Server URL

  • cert.pem

  • key.pem

  • Passphrase

  • Bundle identifier of the app

Integration through CocoaPods

Cocoa Pods is a dependency manager for Objective C & Swift projects that make integration easier. Follow the below steps to integrate the SDK with CocoaPods.

  • Install Cocoa Pods by using the following line in your terminal

sudo gem install cocoapods
  • Next, add the Lemnisk SDK to your Podfile. Copy-paste the below snippet in your Podfile

If you are using SDK version <= 3.8.5 then add the extensions as mentioned below.

platform :ios, 'YOUR_TARGET_PLATFORM_VERSION'

target 'YOUR_TARGET_NAME' do  
    # Lemnisk SDK
    pod 'Lemnisk-iOS-SDK', '3.8.5'
end


target 'NotificationContentExtension' do
  use_frameworks!

  # Lemnisk Notification Content Extension
  pod 'Lemnisk-NotificationContent', '3.8.5'
end

target 'NotificationServiceExtension' do
  use_frameworks!

  # Lemnisk Notification Service Extension
  pod 'Lemnisk-NotificationService', '3.8.5'
end

If you are using SDK version >= 3.8.6 then add the extensions as mentioned below.

platform :ios, 'YOUR_TARGET_PLATFORM_VERSION'

target 'YOUR_TARGET_NAME' do  
    # Lemnisk SDK
    pod 'Lemnisk-iOS-SDK', '3.8.6'
end


target 'NotificationContentExtension' do
  use_frameworks!

  # Lemnisk Notification Content Extension
  pod 'Lemnisk-iOS-SDK', '3.8.6'
end

target 'NotificationServiceExtension' do
  use_frameworks!

  # Lemnisk Notification Service Extension
  pod 'Lemnisk-iOS-SDK', '3.8.6'
end
  • Run the following command to install the SDK

pod install --repo-update

Configuration

App configuration

  • Please enable Push Notifications (You can ignore if you aren't using Push Notification from Lemnisk) and AppGroup capability from our Xcode Signing & Capabilities Tab and use the Same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

  • Then call the setAppGroupID method to set the AppGroup selected in the Xcode's Signing & Capabilities

  • Then call configure() method to initialise the SDK. It will initialise the iOS SDK with writeKey , serverUrl and launchOptions

Usage:

Lemnisk.shared.setAppGroupID(groupId: "your app group id") // This will be something like co.lemnisk.app.ios.bankingdemo
Lemnisk.shared.configure(writeKey: "writekey", serverUrl: "Server Url", launchOptions: launchOptions)

Example:

Lemnisk.shared.setAppGroupID(groupId: "co.lemnisk.app.ios.bankingdemo")
Lemnisk.shared.configure(writeKey: "ABC2rj2", serverUrl: "https://xx-pl.lemnisk.co", launchOptions: launchOptions)

Parameter

Type

Description

writeKey

String

(Mandatory) Write key of the iOS source

serverUrl

String

(Mandatory) Server URL

launchOptions

[UIApplication.LaunchOptionsKey: Any]

(Mandatory) launchOptions at "didFinishLaunchingWithOptions" method

Enabling Debug Logs

If you want to enable debug logs while you integrate and test Lemnisk SDK in you app. You can do so by using the following Lemnisk SDK method.

Lemnisk.shared.setLogLevel(LemniskLogLevel.debug.rawValue)

Now whenever you want to show the Push Notification Authorization prompt to the user, you can call the following Lemnisk SDK method.

Lemnisk.shared.registerForPushNotifications()

If you are using multiple push providers and using SDK version >= 3.8.6 you need to follow below steps.

In your AppDelegate you need to disable swizzling and then only call registerForPushNotifications

// Your code
Lemnisk.shared.setSwizzle(state: false)
Lemnisk.shared.setSwizzleForAll(state: false)
Lemnisk.shared.registerForPushNotifications()
// Your code

After you add above code you need to call our Lemnisk methods in your UIApplicationDelegate methods as mentioned below

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Your code
    Lemnisk.shared.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
    // Your code
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    // Your code
    Lemnisk.shared.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
    // Your code
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // Your code
    Lemnisk.shared.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
    // Your code
}

Rich Push Setup

From iOS 10+, we can show rich media Push Notifications with images, video, audio and carousel. So please configure the below 2 extensions in your project if you don't have them already and configure Lemnisk SDK in them.

Notification Service Extension

We use Notification Service Extension to track the delivery of Push Notifications as well as downloading the Rich Media Push Notification attachments (image/video/audio etc)

  • Add a Notification Service Extension target to your project (File -> New -> Target -> Notification Service Extension)

  • Define the name for the Notification Service Extension in the next step

  • Now please enable the AppGroup capability from our Xcode Signing & Capabilities Tab and use the same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

  • Now modify the NotificationService.swift to look like the following code.

  • If you are using SDK version below 3.8.5 then use the below code

import UserNotifications
import LemniskRichNotification

class NotificationService: LemniskNotificationService {

    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        super.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        super.didReceive(request, withContentHandler: contentHandler)
    }

    public override func serviceExtensionTimeWillExpire() {
        super.serviceExtensionTimeWillExpire()
    }
}
  • If you are using version 3.8.5 and above modify the NotificationService.swift to look like the following code.

import UserNotifications
//if SDK version <= 3.8.5
import LemniskRichNotification
// else if SDK version >= 3.8.6
import Lemnisk

class NotificationService: UNNotificationServiceExtension {
    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        LemniskNotificationService.shared.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        LemniskNotificationService.shared.didReceive(request, withContentHandler: contentHandler)
    }
    
    public override func serviceExtensionTimeWillExpire() {
        super.serviceExtensionTimeWillExpire()
    }
}

If you have multiple push providers and using sdk version >= 3.8.6 you can implement NotificationService as mentioned below.

import UserNotifications
import Lemnisk

class NotificationService: UNNotificationServiceExtension {

    var bestAttemptContent: UNMutableNotificationContent?
    var isLemPush: Bool?
    
    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        self.isLemPush = false
        
        var userInfo: [String: Any]? = bestAttemptContent?.userInfo as? [String: Any]

        if Lemnisk.shared.isLemniskPush(userInfo: userInfo) {
            self.isLemPush = true
            LemniskNotificationService.shared.setAppGroupID(groupId: "your app groupid")
            LemniskNotificationService.shared.didReceive(request, withContentHandler: contentHandler)
        }
        else{
            //other push provider code
        }
    }
    
    public override func serviceExtensionTimeWillExpire() {
        if(self.isLemPush == true){
            super.serviceExtensionTimeWillExpire()
        }
        else{
            //other push provider code
        }
    }
}

Notification Content Extension

This extension can be used if you want to show a carousel slider in a Push Notification.

  • Add a Notification Content Extension target to your project (File -> New -> Target -> Notification Content Extension)

  • Define the name for the Notification Content Extension in the next step.

  • Make sure the deployment target for notification content is set to iOS 10

  • Now please enable the AppGroup capability from our Xcode Signing & Capabilities Tab and use the same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

  • Now modify the NotificationViewController.swift to look like the following code.

import UIKit
import UserNotifications
import UserNotificationsUI
// if sdk version <= 3.8.5
import LemniskNotificationContent
// else if sdk version >= 3.8.6
import Lemnisk

class NotificationViewController:  LemniskNotificationViewController {

    override func viewDidLoad() {
        super.viewDidLoad();
    }

    override func didReceive(_ notification: UNNotification) {
        super.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        super.didReceive(notification)
    }
}
  • Then run pod install. If you are running this for the first time then you may need to update the pod repositories by using running pod install --repo-update. This would install the Lemnisk framework along with the required dependencies for your app extension targets.

Configuring App Groups

Please follow the following procedure if you are using the Xcode Auto Sign, otherwise please scroll below to add the App Groups manually via the Apple Developer Console.

With Xcode Auto Sign

  • Go to App Groups capability from the Xcode’s Singing & Capabilities for all the targets (App,NotificationServiceExtension and NotificationContentExtension) as shown in the following screenshot.

  • Now search for App group and select App Groups

  • Now create the required App Groups Id by inputting a value similar to your Bundle Id (need not be the same as BundleId) which will have group. as the prefix

  • Now finally select group id that we have just created

  • Similarly select the already created same AppGroup for the other two targets - Notification Service Extension and Notification Content Extension.

From Apple Developer Console

  • Goto Identifiers tab in the Apple Developer Console and click on App Groups as shown in the below screenshot.

  • Now tap + to create a new App Group

  • Select App Groups on the next screen as shown below

  • Now fill the Description and the Identifier (App Group name) and click Continue

  • On the next screen, click Register

  • Now go to Identifiers tab, click on your App Bundle identifier

  • Now check on App Groups and click configure

  • In the next step, select the group we have created in the previous step and click continue and then Save

  • Now go to Profile tab and select your profile, if it shows invalid then click Edit and Save. Then download the file and use it in the Xcode.

  • Finally in the Xcode, go to Singing & Capabilities as shown in the following screenshot

  • Now search for App group and select App Groups

  • Now select the App group that we have created earlier in the Apple Developer Console

  • Now repeat steps 6-12 for App extension targets as well (From the Now go to Identifiers step above)

iOS Focus Mode [Update 2021]

With iOS 15 and iPadOS 15, Focus Mode lets you stay in the moment when you need to concentrate or step away from your device. You can customize Focus settings and choose when you want to receive alerts and notifications, while letting other people and apps know when you’re busy. For more information, refer https://support.apple.com/en-in/HT212608

Type of Focus notifications:

  1. active (default)

    • Active is the default interruption level

    • Sounds and vibrations can be played and the screen will light up upon delivery

    • These notifications cannot break through Focus modes.

  2. passive

    • Passive notifications are the notifications that do not require immediate attention

    • No sound or vibration is played when the notification is delivered

    • Examples for passives are such as restaurant recommendations or upcoming sports game updates.

  3. timeSensitive

    • Time sensitive notifications behave similarly to Active notifications

    • Time Sensitive are displayed with a yellow Time Sensitive banner

    • These notifications can break through scheduled delivery and Focus modes

    • Time Sensitive notifications are only be used for notifications that require immediate attention such as an account security or package delivery alerts

    • To enable Time Sensitive notifications, we need to add the xcode capability to our App in Xcode (Time Sensitive Notifications capability) Users can turn off time sensitive notifications for an app.

  4. critical

    • Critical notifications are always delivered immediately and bypass the silent ringer switch

    • These are only available with an approved entitlement and are used for severe weather and local safety alerts

    • The interruption level can be set on the UNNotificationContent object or in the APN's payload with key interruption-level at the apps level

    • Apps are able to change the interruption level prior to delivery by using a Notification Service Extension

Critical notifications are not enabled by default. You need to request Apple to send out critical notifications and Apple will approve it on a case-by-case basis.

Apple will provide you with an entitlement file for critical push notifications once it is approved. Link to the form: https://developer.apple.com/contact/request/notifications-critical-alerts-entitlement/

Build changes

Following capability needs to be added to your Xcode project during the build to enable the time-sensitive notifications

Payload Change

The string values “passive”, “active”, “time-sensitive”, or “critical” correspond to the UNNotificationInterruptionLevel enumeration cases.

Info.plist Configuration

App

  1. Please add the Privacy - Tracking Usage Description (NSUserTrackingUsageDescription) key in your main app Info.plist as this will be used as a description while showing the Tracking description if you would want to enable the IDFA tracking.

  2. To enable/disable the IDFA tracking you can do so by adding the properties LemniskUseIDFA and LemniskShowIDFAPrompt as Boolean to your main app's Info.plist file.

Please find the description of above LemniskUseIDFA and LemniskShowIDFAPrompt below

  • LemniskUseIDFA - Will grant IDFA usage to Lemnisk

  • LemniskShowIDFAPrompt - To whether ask the user for Tracking permission or not

Notification Content Extension

  1. Please update the Notification Content Extension Info.plist's UNNotificationExtensionCategory to Array and add the required categories from the following entries.

    i. carousel

  2. Add the following properties under NSExtensionAttributes

    i. Add property UNNotificationExtensionDefaultContentHidden as String and set its value to YES

    ii. Add property UNNotificationExtensionUserInteractionEnabled as Boolean and set its value to true

Events

Now you can use Lemnisk SDK to send events to Lemnisk.

screen

The screen() method is used to record the screen details whenever a user sees any screen on the application.

Usage:

Lemnisk.shared.screen(screenName, properties, otherIds)

Example:

Lemnisk.shared.screen("home_screen", 
  properties: [
    "variation": "carousel",
    "buttons": 2
  ],
  otherIds: [
    "trackerId": "6791c47a-0178-47bc-8711-86a2c67b2255",
    "email":"john.doe@gmail.com",
    "phone":"9848012345"
  ])

identify

The identify call lets you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about the user, like their email, mobile, any other id etc.

Usage:

Lemnisk.shared.identify(userId, traits, otherIds)

Example:

Lemnisk.shared.identify("cid123",
  traits: [
    "firstName": "John",
    "lastName": "Doe",
    "gender": "Male",
    "age": "27",
    "city": "Mumbai"
  ],
  otherIds: [
    "trackerId": "6791c47a-0178-47bc-8711-86a2c67b2255",
    "email":"john.doe@gmail.com",
    "phone":"9848012345"
  ])

track

The track call lets you record any actions your users perform, along with any properties that describe the action.

Usage:

Lemnisk.shared.track(eventName, properties, otherIds)

Example:

Lemnisk.shared.track("cid123",
  properties: [
    "activityName": "Subscribe",
    "activityType": "buttonClick"
  ],
  otherIds: [
    "trackerId": "6791c47a-0178-47bc-8711-86a2c67b2255",
    "email":"john.doe@gmail.com",
    "phone":"9848012345"
  ])

Parameter

Type

Description

eventName

String

The name of the event you’re tracking

App Events

Following are some of the standard events that Lemnisk SDK collects automatically when you initialize the Lemnisk SDK which has Manual Firing Required as No below.

Event NameDescriptionManual Firing Required

Application Installed

This event is automatically fired when the user installs an application.

No

Application Opened

This event is automatically fired when the user opens an application.

No

Application Updated

This event is automatically fired when the application gets updated.

No

Application Backgrounded

This event should be sent when a user backgrounds the application.

No

Application Crashed

This event should be sent when you receive a crash notification from your app.

Yes (You have to call this explicity from wherever you are handling the crash in your App)

Application Uninstalled

This event should be sent when you receive a user uninstalls the application.

Yes (Generated from Backend)

Application Session Started

This event is automatically fired when a user spends over 10 seconds on the app.

No

Application Session Concluded

This event is automatically fired when a user is inactive for 20 minutes on the app.

No

Application Crashed

Usage

Lemnisk.shared.trackAppCrashedEvent("Crash message here");

Configuring APNS Certificates

Generating .p8 certificate

  1. Go to the Apple developer account and go to Certificates, Identifiers & Profiles

  2. Go to Keys section and click on a new key using Add button(+).

  1. Choose a unique name for the key and select the Apple Push Notification service(APNs) checkbox. Click continue and then confirm.

  1. Note and save the key ID. Click Download to generate and save the key.

  2. Now please share the above Downloaded file along with the Team ID and App Bundle Id

Note

  1. Please note you have to save the above Download key in a secure place because you can't download the key more than once. Do not rename the Auth key file, and provide it to Lemnisk as is.

  2. You will get your Team ID from the Apple Developer Account. Go to Membership tab and get your Team ID visible under Membership details. Your app's bundle ID can be found in Xcode.

Generating .p12 certificate

Lemnisk would need the cert.pem and key.pem files generated for your application to be able to send the App Push Notifications.

Following is the procedure to generate the cert.pem and key.pem files.

Generating the CSR and p12

Open Keychain Access on your Mac (it is in Applications/Utilities) and choose the menu option Request a Certificate from a Certificate Authority

You should now see the following window:

  1. Enter your email address here.

  2. Enter your application name here, for example, I have entered "LemniskDemo". You can type anything you want here, but choose something descriptive. This allows us to easily find the private key later.

  3. Check Saved to disk and click Continue.

If you go to the Keys section of Keychain Access, you will see that a new private key has appeared in your keychain.

Right-click on the new private key and choose Export.

Save the private key as LemniskDemoKey.p12 and enter a passphrase. (Do choose a passphrase that you can recall! Or you won’t be able to use the private key later.)

So log in to the Apple developer console & follow the below steps:

Generating the aps cert

Assuming you have already created the Identifier for your app bundle id, now navigate to the Certificates section in the developer console. Click on the + next to Certificates

Choose the Apple Push Notification service SSL (Sandbox & Production) option and click on Continue

Now select the App Id from the already registered (of your app) list in the Identifier section and then click on Continue

Now click on Choose File and select the CSR file that we have generated above and click on Continue

Now we have successfully generated the aps.cer file, click on the Download button to download the cer file. Let’s say the downloaded file name is aps.cer

Generating the PEM file

So now we have three files:

  1. The CSR

  2. The private key as a p12 file (LemniskDemoKey.p12)

  3. The SSL certificate (aps.cer)

You have to convert the certificate and private key into a format that is more usable. Because our server will need the cert.pem and key.pem file to deliver the push notification, now we will generate them by using the following procedure.

We are going to use the command-line OpenSSL tools for this. Open a Terminal and execute the following steps.

Convert the .cer file into a .pem file:

$ openssl x509 -in aps.cer -inform der -out LemniskDemoCert.pem

Convert the private key’s .p12 file into a .pem file:

$ openssl pkcs12 -nocerts -out LemniskDemoKey.pem -in LemniskDemoKey.p12

 Enter Import Password: 

 MAC verified OK
 
 Enter PEM pass phrase: 

 Verifying - Enter PEM pass phrase: 

You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file.

Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Now let’s try to test whether the certificate works, by using our SSL certificate and private key:

$ openssl s_client -connect gateway.push.apple.com:2196 -cert LemniskDemoCert.pem -key LemniskDemoKey.pem

    Enter pass phrase for LemniskDemoCert.pem:

Now please share the following with your account manager for us to be able to send push notifications

  1. cert.pem and key.pem (Generated above)

  2. passphrase (if any given in the above steps)

  3. bundle identifier of the app

FAQs

Q1. What is the minimum iOS version supported by the Lemnisk iOS App SDK?

Ans: iOS 13 or higher is supported.

Q2. Can I install the Lemnisk SDK via Carthage?

Ans: No, as of now we only support integration via Cocoapods.

Q3. How does the SDK handle different client/server errors?

Ans: Our SDK isolates any errors that occur internally and wouldn't affect your App.

Contact Us

If you have an unanswered question or to know more about the Lemnisk Android SDK you can contact us.

Last updated