0

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

Carl Henretti
  • 457
  • 2
  • 7
  • 17

1 Answers1

0

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()


}
Maddy
  • 1,660
  • 11
  • 24
  • thanks but it doesn't work either... I don't understand why didreceiveremotenotification isn't called... :/ – Carl Henretti May 28 '17 at 12:33
  • Did u received the notification? If yes. then which version if IOS u r using? – Maddy May 28 '17 at 12:39
  • the newest, 10.3.3 or something... Yeah I receive the notification, this part works perfectly, the thing is that when I save the value in didReceiveRemoteNotification (with synchronizing) and then directly start the app theough Xcode, it says false even though it had to he true because I DID receive the notification... I don't get it – Carl Henretti May 28 '17 at 12:41
  • add an alert in `didRegisterForRemoteNotificationsWithDeviceToken` and `didFailToRegisterForRemoteNotificationsWithError` with success and failure message. It will show whether these delgates are called or not. – Maddy May 28 '17 at 12:45
  • See updated answer may be the issue is because of the IOS version i.e ios>10 – Maddy May 28 '17 at 13:20