Search code examples
iosswiftxcodeswift5

Detect if App was Launched From Tapping Local Notification Swift


I would like to know how to detect if my app was launched from the user tapping a local notification.

I am currently using the method userNotificationCenter(_:didReceive:withCompletionHandler:) My app correctly detects that the app was launched from a notification with this method only when the app is in still active. If I end the app by swiping it up in the app switcher, then tapping on a notification opens the app but does not register in the userNotificationCenter(_:didReceive:withCompletionHandler:).

I previously set UNUserNotificationCenter.current().delegate to self in viewDidLoad(). Some people said to set it in application(_:didFinishLaunchingWithOptions:) instead, and I tried that like this:

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    
    UNUserNotificationCenter.current().delegate = self
    
    return true
}

However, the issue remains.

My Question: How do I detect if my app was launched from the user tapping a local notification, whether the app is active or inactive?

Swift version: swift 5 Xcode version: Xcode 13


Solution

  • Look in the options for your scene delegate willConnect method or (if there is no scene delegate) your app delegate willFinishLaunching method. This tells you how you got launched.