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.
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
inAppDelegate.swift
(3) In
didFinishLaunchingWithOptions
enable/disable feature(4) For device token
(5) If error
In case notification is received delgate that should be called is: