Search code examples
iosswiftnotificationsnsnotificationcenter

How to determine whether the app is opened from NotificationCenter (Local Notification) or the app icon when app is killed


My App receives a local notification Not a remote Notification. How can I know if the app is opened by pressing the notification and not the app icon when the app is killed( Not running in background or foreground). Previosuly, I used the following method

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

however this function is deprecated as of iOS 10

[UIApplication.LaunchOptionsKey.loaclNotification] != nil)

and apple documentation suggests to use the following method.

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

}

This method is called only when the app is in the foreground or background. Any help will be appreciated


Solution

  • How can I know if the app is opened by pressing the notification and not the app icon

    As you said, implement the UNUserNotificationCenterDelegate method didReceive. If the user tapped your notification, it will be called, launching your app if it isn’t running.