Search code examples
iosswiftlocalnotification

How to differentiate between whether a notification is a local or remote notification when app Starts in IOS


Previously i used the following code to differentiation whether my notification is local or remote when the app starts

    func application(_ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: 
    [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    if (launchOptions?[UIApplication.LaunchOptionsKey.localNotification] != nil)
    {


    }
    if (launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil)
    {


    }
    }

The conditions is that my app is killed and I am opening it from notification.

The problem is that this method

if (launchOptions?[UIApplication.LaunchOptionsKey.localNotification] != nil)
{


}

is deprecated and the following method isnot called when the app is opened from notification center

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {}

Solution

  • You can check the notification type in userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: too,

    Class hierarchy is:

    UNNotificationResponse > UNNotification > UNNotificationRequest > UNNotificationTrigger

    There are 4 types of triggers in UNNotificationRequest:

    • UNLocationNotificationTrigger
    • UNPushNotificationTrigger
    • UNTimeIntervalNotificationTrigger
    • UNCalendarNotificationTrigger

    Just use,

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
        if response.notification.request.trigger is UNPushNotificationTrigger {
            print("remote notification");
        }
    
    }