Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get userInfo when user click in notification when app is closed?

I'm doing an app that schedule local notifications and save an userInfo. That's part its ok.

But when app is closed, Notification appear, but when user click, the method is not called and I can't handle userInfo.

I saw that there's a new way to receive notification with UNUserNotificationCenter. But is not working too.

That's my implementation in AppDelegate:

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

    let lNotification = UILocalNotification()
    lNotification.userInfo = response.notification.request.content.userInfo

    applicationWorker.manage(localNotification: lNotification)
}

Anyone to help me? I saw all the questions related here and didn't found anything.

Thanks!

EDIT:

If someone are looking for a solution, I added UNUserNotificationCenter.current().delegate = self in didFinishLaunchingWithOptions and it worked.

like image 701
Rafaela Lourenço Avatar asked Mar 26 '18 20:03

Rafaela Lourenço


Video Answer


1 Answers

From iOS 10 onwards, the method you mention should be called whether app is opening from background or inactive state. Perhaps you are not accessing the userInfo correctly. The example below works for me.

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

    let userInfo = response.notification.request.content.userInfo
    if let yourData = userInfo["yourKey"] as? String {
        // Handle your data here, pass it to a view controller etc.
    }
}

Edit: as per the edit to the question, the notification centre delegate must be set in the didFinishLaunching() method, or the method above will not get called.

UNUserNotificationCenter.current().delegate = self
like image 152
Chris Avatar answered Sep 17 '22 02:09

Chris