Mobile SDK

Messangi SDK for iOS

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 in 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.

Create, if not exist, a folder with the name “Frameworks” inside the project, (create folder by right clicking on the left panel and select New Group) then drag and drop the file MessangiSDK.framework into the folder Frameworks. A pop-up window will be displayed, verify you are checking the option copy if needed. Now the .framework file exists into the project.

 Framework

Now go to the section Embedded Binaries, in the configuration section of your application and select the plus sign (+) and in the popup window select the framework.

 Embedded Binaries

The Support Team will send you a file with name 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.

 Messangi-Info.plist

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

In the class AppDelegate you must implement the protocol 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.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessangiProtocol{
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // MessangiSDK
        Messangi.sharedInstance().delegate = self
        Messangi.configure()
        Messangi.sharedInstance().register(withUserID: "Token")
        
        //Register APNS
        //Request permission to receive notifications
        registerForRemoteNotification()
        
        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.

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

    //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 {
                    self.getNotificationSettings()
                    print("Something went wrong")
                }
            }
            UIApplication.shared.registerForRemoteNotifications()
        } else if #available(iOS 9, *) {
            UIApplication.shared.registerForRemoteNotifications()
            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.registerForRemoteNotifications()
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        }
    }
    
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            guard settings.authorizationStatus == .authorized else { return }
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

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.

 Messangi-Info.plist

 Messangi-Info.plist

In the file AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessangiProtocol{
    ....
    //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) {
        Messangi.sharedInstance().registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Remote notification support is unavailable ", error)
    }
    ....
}

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

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessangiProtocol{
    ....
    // 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 is displayed, none of the above methods will be invoked. For this case we recommend using the applicationDidBecomeActive function of the AppDelegate.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessangiProtocol{
    ...
    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:

Objective-C: - UIBackgroundFetchResultNewData: New data added. - UIBackgroundFetchResultNoData: No new data. - UIBackgroundFetchResultFailed: A connection or transmission error occurred.

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.

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)
    Messangi.sharedInstance().unRegisterUser()

Example

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