Instructions on how to connect mobile push notifications (iOS)

1. Connecting the library

This library is distributed using Cocoapods. To use it, a dependency must be added to the Podfile:

«pod "enkodpushlibrary"» 

enkod allows you to use Apple Push Notification System and Firebase Cloud Messaging to send push notifications. To use FCM you need to import Firebase library.

2. Adding Push Notifications to a project

You need to add push notifications to your project so that the user can receive them. To do this, go to Targets to your project and select the Signing & Capabilities. Next, in Capabilities add Push Notifications. In this section specify your Team. Also specify your BundleID in the section General.

To use FCM in an application, you must download GoogleService-Info.plist from the Firebase console and place it in the application folder (a .p8 certificate for the application must be added to the console beforehand).

3. Registering the application with Apple Push Notification Service (APNs)

Registration is necessary to prepare the app for push notifications. To do this, add an APN to the AppDelegate the following code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions 
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    PushNotificationService.setAccount("account")
    PushNotificationService.registerForPushNotifications()   
    if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
             PushNotificationService.notificationData(notification)
         }  
    return true
} 

If FCM is used, the method will look as follows:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    PushNotificationService.setAccount("account")
    PushNotificationService.registerForPushNotifications() 
    FirebaseApp.configure()
    Messaging.messaging().delegate = self
    if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
             PushNotificationService.notificationData(notification)
         }  
    return true
}

where account is the system name of your enKod account (ask your account manager)

This method will ask the user for permission to send notifications on the first run and if the user approves, it will register the app in APNs. Then, if the app has access to send notifications, the next time the app is launched, it will only register the app in APNs.

4. Application device token registration

To send push notifications, you need your app's device token. To register it, add the following code to AppDelegate:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    PushNotificationService.setDeviceToken(deviceToken, account: "account")
}

If FCM is used, the method will be as follows:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
}               

This method processes the device token and sends it to the ISP with the specified account header.

func application(_ application: UIApplication, 
didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)") 
}  

This method will generate an error when receiving device token.

Also the following extension must be added to use FCM:

extension AppDelegate: MessagingDelegate {
  func messaging( _ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?)         {
      PushNotificationService.setDeviceToken(fcmToken ?? "")
  }
}

5. Configuring the processing of push notification opening

Add the following code to the appropriate methods AppDelegate:

func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {    
    PushNotificationService.registerForPushNotifications()
    UNUserNotificationCenter.current().delegate = self                        
    if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
        PushNotificationService.notificationData(notification, account: "account")
    }
    return true
}                        

This method AppDelegate method will be called when the application is fully unloaded from memory and a push notification occurs. It is also necessary to declare a delegate to handle other push notification scenarios.

func application(_ application: UIApplication, 
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {        
    PushNotificationService.notificationData(userInfo, account: "account")
    completionHandler(.newData)
}                
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
    didReceive response: UNNotificationResponse, 
    withCompletionHandler completionHandler: @escaping () -> Void) {                        
    let notification = response.notification.request.content.userInfo
    PushNotificationService.notificationData(notification, account: "account")
    completionHandler()
    }
}  

where account is the system name of your enKod account (ask your account manager)

These methods AppDelegate are called when the application is in the active state and a push notification occurs.

6. Changing the key in Info.plist to make URL requests work correctly

It is necessary to go to the Info.plist file and add the following key with the value:

7. Configuring the display of push notification when the application is open

Add the following method UNUserNotificationCenterDelegate в AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification:
UNNotification, withCompletionHandler completionHandler: @escaping 
(UNNotificationPresentationOptions) -> Void) {
    if #available (iOS 14.0, *) {
        completionHandler ([. list, .banner, .sound])
    } else {
        completionHandler ([. alert, .badge, .sound])
    }
}  

This method allows you to configure notifications to appear even when the app is open.

Push notifications can contain deeplink. To get information about deeplink in a push notification you need to add the following code:

class ViewController: UIViewController {    
    override func viewDidLoad() {
        super.viewDidLoad()                        
        PushNotificationService.subscribeDeeplink(self)
    }
}                
extension ViewController: PushNotificationServiceDelegate {
    func getDeeplink(_ deeplink: String) {
        print(deeplink)
    }
}       

First, you need to subscribe to receive deeplink, and then when you send a push with the embedded deeplink value, the method will be called getDeeplinkmethod, which has a parameter with the deeplink value as a string. To unsubscribe from receiving deeplink add the following code:

PushNotificationService.unsubscribeDeeplink()    

Note: it is worth noting that getting the deeplink value is only possible if the push stores deeplink information. In other cases getDeeplink method will not be called.

9. Push notification model

It is possible to get the push notification model by subscribing to the delegate PushNotificationServiceDelegate:

class ViewController: UIViewController {    
    override func viewDidLoad() {
        super.viewDidLoad()                        
        PushNotificationService.subscribeDeeplink(self)
    }
}                
extension ViewController: PushNotificationServiceDelegate {
    func getPushData(_ pushData: PushData) {
        print(pushData)
    }
}    

10. Pushback from the pooches

To be able to unsubscribe from pooches, call a method and pass an account value to it.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()          
        SessionService.delegate = self
        PushNotificationService.unsubscribePush(account: "account")
    }
}                
extension ViewController: SessionServiceDelegate {
    func sessionCreated() { }
    func sessionStarted() { }
    func pushSubscribed() { }
    func pushUnsubscribed() { }
    func pushClicked() { }
    func tokenRefreshed() { }
    func failure(error: Error) { }    
} 

where account is the system name of your enKod account (ask your personal manager)

Methods and conditions of triggering:

  • sessionCreated session has been successfully created and session ID as well as token are stored in UserDefaults
  • sessionStarted session with previously created ID successfully started
  • pushSubscribed subscription to push notifications successfully completed
  • pushUnsubscribed unsubscribe to push notifications successfully completed
  • pushClicked push notification action successfully sent to the server
  • tokenRefreshed token was updated and sent to the server
  • failure an error occurred in one of the requests

Use the following code to get sessionID:

PushNotificationService.getSessionID

Use the following code to get token:

PushNotificationService.getToken   

11. RichPush processing

In order to implement the ability to unfollow a push notification with an image, you need to add a target Notification Service Extensionin which it is necessary to override the method didReceive.

The following fields must be passed for this functionality to work:

%"image_url" image address where the displayed image will be loaded
"mutable-content" true, to allow modification of the received push before displaying it

For dynamic button processing, the notification should contain a “buttons” field with the following structure:

[{
    "id": "button1",
    "label": "text on button",
    "action": "",???
    "link": "https://somewhere.com" / "https://testApp/mainScreen"
}] 

It is also necessary to register notification categories with actions created on the basis of passed buttons. Example of button processing:

if let buttons = apnsData["buttons"] as? [Any] {
    var acts: Array = []
        for b in buttons{
            let but = b as? NSDictionary
            let id = but?["id"] as! String
            let title = but?["label"] as! String
            let action = UNNotificationAction(identifier: id, title: title, options:
            [.foreground])//.foreground нужен для открытия приложения 
            перед открытием ссылки
        acts.append(action)
    }    
let cat = UNNotificationCategory(identifier: "cat1",
actions: acts, intentIdentifiers: [], options: [])    
    var categories = Set()
    categories.insert(cat)
    UNUserNotificationCenter.current().setNotificationCategories(categories)
}else{
    var categories = Set()
    categories.insert(UNNotificationCategory(identifier: "cat1", 
    actions: [], intentIdentifiers: [], options: []))
    UNUserNotificationCenter.current().setNotificationCategories(categories)
}     

Push notification model

Message model

{
    "aps": {
            "alert": {
                "title": "Title",
                "subtitle": "Subtitle",
                "body": "Body"
                },
            "buttons":[
                {
                    "id": "button1",
                    "label": "text on button",
                    "action": "",???
                    "link": "https://somewhere.com"	
                    },
                {
                    "id": "button1",
                    "label": "text on button",
                    "action": "",???
                    "link": "https://somewhere.com"
                    }
            ]
            "sound": "default",
            "badge": 12,
            "category": "CATEGORY",
            "personId": "123",
            "messageId": "321",
            "intent" : "0",
            "url": "https://url.com",
            "mutable-content": 1, 
            "image-url": "https://picture.com"
    }
}  

Data value

%"alert" information for displaying notifications
%"title" notification title
"subtitle" notification subtitle. Additional information
"body" notification content
"sound" notification sound. If this parameter is not passed, there will be no sound when the notification is received
%"badge" number displayed on the application icon. Specify 0 to remove the current icon, if any
%"category" notification type. This string must match the identifier to one of the objects you register at startup time
%"personId" user ID
"messageId" message ID
%"intent" the action that will be performed when the button is pressed. If “0”, the application will be opened and the dynamic link will be passed there for further processing, if “1” - the link will be opened in the browser, if “2” - the application will be opened.
"url" dynamic link or for opening in a browser
"mutable-content" flag allowing to change the content of the push before displaying it. Used to allow a large image to be displayed when the push is clicked (held) (Rich push)
%"image-url" link containing the address of the image in the push. Used to be able to show a large image when clicking (holding) on a push
Last modified: 2023.12.13 10:37 by Anastasia Aniskova