How to properly implement a custom push notification handling (UNNotificationCenterDelegate)?

There are some cases when In-app messages chained from a Push notification does not show up in iOS.

If a push notification is sent and it has an In-app message chained to it, the message is not displayed when the push is opened and the open action is not tracked. This is caused by incorrect implementation of a custom notification center delegate.

Procedure

  1. Implement the UNUserNotificationCenterDelegate protocol in the app delegate. This way the Leanplum’s logic and custom one is executed automatically and smoothly. Note that Leanplum swizzles methods from the application delegate.

Code example:

import UIKit
import Leanplum
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

// MARK: - Push Notifications
//iOS-10
if #available(iOS 10.0, *){
let userNotifCenter = UNUserNotificationCenter.current()

// Set the delegate to the AppDelegate
userNotifCenter.delegate = self

userNotifCenter.requestAuthorization(options: [.badge,.alert,.sound]){ (granted,error) in
//Handle individual parts of the granting here
}
UIApplication.shared.registerForRemoteNotifications()
}
//iOS 8-9
else if #available(iOS 8.0, *){
let settings = UIUserNotificationSettings.init(types: [UIUserNotificationType.alert,UIUserNotificationType.badge,UIUserNotificationType.sound],
categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
//iOS 7
else{
UIApplication.shared.registerForRemoteNotifications(matching:
[UIRemoteNotificationType.alert,
UIRemoteNotificationType.badge,
UIRemoteNotificationType.sound])
}

// Leanplum integration and other logic…
return true
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}

What's next:

Populate this paragraph if there are any related topics.


Was this article helpful?
Have more questions? Submit a request