3

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

But when the app is closed, if a Notification appears and the user clicks, the method is not called and I can't handle userInfo.

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

I've tried it that way, but I did not succeed:

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.
    }
}

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
        // Handle your data here, pass it to a view controller etc.

}

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

Roberto Pinheiro
  • 1,260
  • 13
  • 30
  • Why you create new instance of UILocalNotification() in didReceive method? What is applicationWorker? Could you show the code of applicationWorker and its manage() method? – Anton Novoselov Mar 27 '18 at 18:30
  • @AntonNovoselov Thanks for the reply, however, this implementation of the method is not the point. The problem is that when the app launches by notification, this function was not called. – Roberto Pinheiro Mar 27 '18 at 19:36
  • @AntonNovoselov The point is, how do I call the function when I open the application by clicking the notification. I appreciate your help! – Roberto Pinheiro Mar 27 '18 at 19:46
  • check my answer - check if you registered for notifications – Anton Novoselov Mar 27 '18 at 20:08

1 Answers1

0

Have you registered for notifications? If not, add this to AppDelegate 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")
            }
        })
        UNUserNotificationCenter.current().delegate = self
Anton Novoselov
  • 769
  • 2
  • 7
  • 19