简体   繁体   中英

didReceiveRemoteNotification not called - why?

I'm having a problem with my app and the UserNotifications framework. I've got a main view controller with a sendNotification()-function as the following:

let content = UNMutableNotificationContent()
        content.title = "Water Reminder"
        content.body = "What about a glass of water?"
        content.sound = UNNotificationSound.default()

        let testTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: false)

        let identifier = Int(arc4random_uniform(999999999))

        let request = UNNotificationRequest(identifier: "\(identifier)", content: content, trigger: testTrigger)

        center.add(request, withCompletionHandler: {
            (error) in
            if let error = error {
                print("Didn't add notification request. \(error)")
            }

        })

The trigger is just for testing. Well, after 30 seconds, I receive the notification. To that point, everything is fine. The problem is: when it has received a reminder, it should call the didReceiveRemoteNotification()-function in the app delegate, but it doesn't. Here's my function:

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

    UserDefaults.standard.set(true, forKey: "didReceiveRemoteNotification")
}

So, I have received the notification, inserted in the didFinishLaunchingWithOptions()-function this line of code:

print("\(UserDefaults.standard.bool(forKey: "didReceiveRemoteNotification")")

and it gives me false, even though I HAVE received a notification. How is that possible?

In the capabilities section, background modes for notifications and background fetch are activated as well as push notifications. App delegate and view controller have both imported UserNotifications, are added as UNUserNotificationCenterDelegate and both have got a center.delegate = self one of code. Why doesn't it work? Why does my didReceiveRemoteNotification()-function not get called?

Thanks for your help...

Add this line.

UserDefaults.standard.synchronize()

From Apple Docs: Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization

**Update: ** For IOS 10 use UserNotifications framework

(1) Import UserNotifications framework

(2) Add protocol UNUserNotificationCenterDelegate in AppDelegate.swift

(3) In didFinishLaunchingWithOptions enable/disable feature

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

}
application.registerForRemoteNotifications()

(4) For device token

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenAsString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenAsString)


}

(5) If error

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print(error)
}

In case notification is received delgate that should be called is:

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

    completionHandler(UIBackgroundFetchResult.noData)

UserDefaults.standard.set(true, forKey: "didReceiveRemoteNotification")
UserDefaults.standard.synchronize()


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM