Push Notification Implementation
library_add_check

Prerequisites

Make sure you have created APNS certificate and uploaded it to MoEngage dashboard as mentioned in APNS Certificate/ PEM file before testing push notification.

Register For Notification

Follow the below steps to register for remote notification

1. Add Push Notifications capability in the main target by navigating to Target -> Signing &  Capabilities.

Screenshot 2024-02-07 at 10.19.35 AM.png

2. Call SDK's registerForRemoteNotification(withCategories:andUserNotificationCenterDelegate:) to initiate registration of remote notifications as shown below :

Swift Objective-C
MoEngageSDKMessaging.sharedInstance.registerForRemoteNotification(withCategories: nil, andUserNotificationCenterDelegate: self)

You can optionally pass the categories and delegate to get the callback for the UserNotificationCenter delegate method as mentioned in the below Callback section

info

Note

  • You can send the set of categories(UNNotificationCategory) for supporting Notification actions. Get more info regarding notification actions here.

Provisional Push

Register for Provisional push

Call SDK's registerForRemoteProvisionalNotification(withCategories:andUserNotificationCenterDelegate:)  function to track notification received impression as shown below.

Swift Objective-C
MoEngageSDKMessaging.sharedInstance.registerForRemoteProvisionalNotification(withCategories: nil, andUserNotificationCenterDelegate: self)

AppDelegate swizzling in SDK

AppDelegate Swizzling is used for intercepting the methods of the AppDelegate class in iOS apps. It allows third-party libraries or SDKs to integrate into the app and handle certain system interactions, such as push notifications and deep linking, without requiring manual setup by developers.

Default behavior

By default, the MoEngage SDK swizzles the AppDelegate Class to get all the callbacks related to Push Notifications, and also we have applied method swizzling for UserNotificationCenter delegate methods. This is to ease the integration of the SDK, and this is introduced from the SDK version 5.0.0.

Disabling AppDelegate Swizzling in the MoEngage SDK

You should disable AppDelegate Swizzling if you do not want MoEngage SDK to implicitly handle the callbacks. To disable swizzling, add the flag MoEngageAppDelegateProxyEnabled in the app’s Info.plist file and set it to bool value NO.

In the following sections, we have provided the SDK methods to be called when you get callbacks related to push notifications. Most of them will not be needed in case swizzling is enabled; the same will be mentioned in the description.

Now after registering for push, the below-given callback methods will be called.  In case you have disabled swizzling, call the respective MoEngage SDK methods for the callbacks as shown below :

Callback received on registering for notification

Swift Objective-C
//Remote notification Registration callback methods
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  //Call only if MoEngageAppDelegateProxyEnabled is NO
  MoEngageSDKMessaging.sharedInstance.setPushToken(deviceToken)
}


func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  //Call only if MoEngageAppDelegateProxyEnabled is NO
  MoEngageSDKMessaging.sharedInstance.didFailToRegisterForPush()
}

Callback on receiving Push Notifications:

Swift Objective-C
// MARK:- UserNotifications Framework callback method
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
    //This is to only to display banner and enable notification sound
    completionHandler([.sound,.banner])
    
}
info

Note

  • The above callback is received when notification is delivered when the application is in the foreground.

Callback on clicking Push Notifications:

Swift Objective-C
// MARK:- UserNotifications Framework callback method

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //Call only if MoEngageAppDelegateProxyEnabled is NO
MoEngageSDKMessaging.sharedInstance.userNotificationCenter(center, didReceive: response) //Custom Handling of notification if Any let pushDictionary = response.notification.request.content.userInfo print(pushDictionary) completionHandler(); }

Refer to the Apple doc for more information on the above delegate methods.

info

Note

  • To receive callbacks on receiving and clicking of push notifications, please make sure to conform to the UNUserNotificationCenterDelegate. You can pass it as a parameter in the notification register method as mentioned above, or explicitly confirm it by using the UNUserNotificationCenter.current().delegate = self statement

Notification Click callback in the App:

You can use the MoEngageMessagingDelegate to receive the  notificationClicked(withScreenName:andKVPairs:) callback with key-value pairs and screen name when the MoEngage notification is clicked by the user.

Here's an example of how you can implement this in your code:

Swift Objective-C
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MoEngageMessagingDelegate{
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      // Set the delegate 
      MoEngageSDKMessaging.sharedInstance.setMessagingDelegate(self)

      //Rest of the implementation
}

// Notification Clicked Callback
func notificationClicked(withScreenName screenName: String?, andKVPairs kvPairs: [AnyHashable : Any]?) {
        if let screenName = screenName {
            print("Navigate to Screen:\(screenName)")
        }
        
        if let actionKVPairs = kvPairs {
            print("Selected Action KVPair:\(actionKVPairs)")
        }
}
  
// Notification Clicked Callback with Push Payload
func notificationClicked(withScreenName screenName: String?, kvPairs: [AnyHashable : Any]?, andPushPayload userInfo: [AnyHashable : Any]) {
        
        print("Push Payload: \(userInfo)")
        
        if let screenName = screenName {
            print("Navigate to Screen:\(screenName)")
        }
        
        if let actionKVPairs = kvPairs {
            print("Selected Action KVPair:\(actionKVPairs)")
        }
}
}

By implementing the notificationClicked(withScreenName:andKVPairs:) method in your custom messaging delegate class, you can access the screen name and key-value pairs associated with the clicked notification. You can then perform any required action based on this information.

Previous

Next

Was this article helpful?
2 out of 4 found this helpful

How can we improve this article?