AppDelegate method is only called from a notification when the app is already open

821 views Asked by At

I'm trying to have a push notification take the user to a specific view controller when pressed on it.

I currently have this in my AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        if let error = error {
            print(error.localizedDescription)
        } else {
            application.registerForRemoteNotifications()
        }
    }
    
    UNUserNotificationCenter.current().delegate = self

    return true
}

When I press on the notification and open the app from the background, none of these are being called:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
    completionHandler([.alert, .sound, .badge])
}

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

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

}
1

There are 1 answers

0
Stamenkovski On BEST ANSWER

if your app is not running in the background you will handle notification in didFinishLaunchingWithOptions like this

let notificationInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String : Any]

and if your app is running in background/foreground you will handle notification tap in

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