iOS Integration

MessangiSDK for iOS is a library for push events processing on iOS platform, it’s developed from Cocoa Touch Framework and it’s compatible with Objective-C and Swift.

The minimum compatible version using SDK integration is iOS 8.


In iOS, push notifications can’t be registered or received in the Simulator, so you must have a physical device to perform tests with MessangiSDK.

Include the library SDK has been uploaded to Cocoapods, so adding this framework to your app's project can be more straightforward.

In order to add Messangi SDK to your project follow the steps below:

  • If you don't have Cocoapods installed, then run in terminal window

      $ sudo gem install cocoapods
  • In your terminal window run $ cd into your project directory.

      $ pod init
  • Create a Podfile. This can be done by running

  • Open your Podfile generated in the previous step. In the first line you should specify the platform and version supported.

      platform :ios, '9.0'
  • Add MessangiSDK in the pod list (let 'MyApp' be your app's name)

      target 'MyApp' do
        pod 'MessangiSDK'

To add dependencies run in your project directory:

  pod install


Make sure to always open the Xcode workspace created by Cocoapods instead of the original project file when building your project:

  $ open MyApp.xcworkspace

Configuration of MessangiSDK

The Support Team will send you a file named Messangi-Info.plist, this must be added by dragging & dropping from the location that has it to the project, at the same level of AppDeletage.swift.


To continue with the configuration of the library, go to the AppDelegate.swift of your application. This is the main configuration file.

The class AppDelegate must implement the protocols UNUserNotificationCenterDelegate and MessangiProtocol, this will force you to implement the function pushReceived (_ message: Message, from workspace: Workspace). Then you must add the Messangi configuration in the function didFinishLaunchingWithOptions.

import MessangiSDK
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessangiProtocol{
    //Overwrite your function
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // MessangiSDK
        Messangi.sharedInstance().delegate = self
        Messangi.sharedInstance().register(withUserID: "Token")
        //Register APNS
        //Request permission to receive notifications
        return true
    func pushReceived(_ message: Message, from workspace:Workspace) {
        // This method will be called every time the user receives a push notification
        // via Messangi and the field title and body has been retrieved from the server.
        // Use this method to display the content of the notification


The Token must have at least 7 characters.

Permissions for Notifications

In newer versions of iOS it’s necessary to request a special permission to submit and receive notifications. The library does not request this permission, so you must request it in your application. In the AppDelegate.swift file

    //Register permissions to receive notifications
    func registerForRemoteNotification(){
        if #available(iOS 10.0, *){
            let center = UNUserNotificationCenter.current()
            center.delegate =  self
            center.requestAuthorization(options: [.alert, .sound, .badge]) {
                (granted, error) in
                if !granted {
                    print("Something went wrong")
        } else if #available(iOS 9, *) {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
        } else if #available(iOS 8, *){
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            guard settings.authorizationStatus == .authorized else { return }

Configuration for PUSH Notifications

Push notification settings are handled in your application directly, so you can follow any guide to complete this integration. You just have to remember that once the device is registered to receive push notifications, the received deviceToken must be added to the Messangi library using the method Messangi.sharedInstance().registerDeviceToken(deviceToken).

Below we present the most common implementation, compatible with iOS 8 and higher.

In App Capabilities section you must enable the Push Notifications and Background Modes sections, and enable Background Fetch and Remote Notifications.


In the AppDelegate.swift file:

    //iOS 9 and lower
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        Messangi.sharedInstance().registerDeviceToken(deviceToken as Data?)
    //iOS 10.0
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Remote notification support is unavailable ", error)

Reception and Processing of Push Notifications

The reception of push notifications occurs in the application itself, so it is the responsibility of your application to implement what you consider necessary for the Processing of notification.

Once the notification is received it must be sent to the library using the method Messangi.sharedInstance().processRemoteNotification(userInfo, fetchCompletionHandler: completionHandler) for processing.

If your application receives notifications from multiple sources, you must implement your own flow for that notifications and transmit to the Messangi library only those coming from the Messangi Campaign Manager.

Below we present the most common implementation, compatible iOS8 and above for receiving push notifications (in AppDelegate class file):

    // iOS9
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        Messangi.sharedInstance().processRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
    @available(iOS 10.0,*)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        //Invoked when a notification is sent to a foreground application.
        let userInfo = notification.request.content.userInfo
        Messangi.sharedInstance().processRemoteNotification(userInfo, fetchCompletionHandler: nil)
        //If you want to show a notification in the foreground, uncomment the following line
        //completionHandler([.alert, .sound])
    @available(iOS 10.0, *)
    private func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        //You were called so your application would know which action the user selected for a given notification.
        let userInfo = response.notification.request.content.userInfo
        Messangi.sharedInstance().processRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)


If your application is in the background and is not opened from the notification when it's displayed, none of the above methods will be invoked. For this case we recommend using the applicationDidBecomeActive function of the AppDelegate.

    //Overwrite your function
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in background, optionally refresh the user interface.
        Messangi.sharedInstance().getUnreadMessages(handler: nil)

UIBackgroundFetchResult (Optional)

As you can see, many of the library’s methods make use of the UIBackgroundFetchResult to notify when they finish their execution. This is because many of these methods include http communication so they resolve asynchronously.

The Messangi Library responds with the 3 official constants from the Apple documentation, these are:

In Objective-C:

  • UIBackgroundFetchResultNewData: New data added.

  • UIBackgroundFetchResultNoData: No new data.

  • UIBackgroundFetchResultFailed: A connection or transmission error occurred.

In Swift:

  • UIBackgroundFetchResult.newData: New data added.

  • UIBackgroundFetchResult.noData: No new data.

  • UIBackgroundFetchResult.failed: A connection or transmission error occurred.

In case you don’t need to use this you can ignore it and let the operating system handle it, if you want to make a specific update, you should only implement your own BackgroundHandler and pass it, instead of the one provided by the System.

Authentication (Optional)

In some cases the developer may wish to manipulate the user’s life cycle within the application, for example allowing login and logout of different users.

For these cases the library has the following methods:

  • Register User

        let userId:String = ...;
        Messangi.sharedInstance().register(withUserID: userID)
  • Delete user registration (This will also remove all notifications, geofences and beacons registered in the device)



You can check a complete example of the file In the following link

Deep Links

After processing the notification the SDK will post the notification on pushReceive method.

func pushReceived(_ message: Message, from workspace:Workspace) {
    // This method will be called every time the user receives a push notification
    if let data = .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: message.metaData, options: []) as? [String: Any]
        } catch {
    let deeplink = data['deep-link']
    // Handler your deeplink and redirect according.


In some cases, such as a bad connection, the pushReceived method may not be called, so we always recommend checking and handling the deepLink data in didReceiveRemoteNotification and  willPresentNotification

Was this article helpful?
0 out of 0 found this helpful



Article is closed for comments.