iosswift4uilocalnotificationuserinforemote-notifications

How to handle localNotifications when app is closed


I've searched in all questions here but no solution worked.

I scheduled localNotifications with a userInfo option. When app is in foreground, the notification arrived and a can handle perfectly with this function that system calls by itself.

But the problem is, when app is closed, this functions are not called and I can't handle the data that I need.

I've tried get userInfo in that function in appDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if let localUserInfo = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? [AnyHashable: Any] {

        // My implementation
    } else if let remoteUserInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {

        // My implementation
    }
    return true
}

But.. Didn't work...

Someone could help me please?

Thanks in advance.


Solution

  • Have you registered for notifications? In didFinishLaunchingWithOptions():

        // Register Notifications
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
    
                    if granted {
                        print("User notifications are allowed")
                    } else {
                        print("User notifications are NOT allowed")
                    }
                })
                application.registerForRemoteNotification()
                UNUserNotificationCenter.current().delegate = self
    

    Then you should catch local notifications in UNUserNotificationCenterDelegate method:

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