Ahmed
Ahmed

Reputation: 1359

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

Upvotes: 0

Views: 270

Answers (2)

Wano Logic
Wano Logic

Reputation: 1

One reason of not getting didReceive call after app is killed is not setting delegate on start of the app. In didFinishLaunchingWithOptions method delegate must be set

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
 center = UNUserNotificationCenter.current()
 center.delegate = self

}

Upvotes: 0

matt
matt

Reputation: 535889

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.

Upvotes: 1

Related Questions