Tearing my hair out tying to get push notifications to work in iOS10. Current setup:
in func application(_ application: UIApplication, didFinishLaunchingWithOp
I struggled with this for a full day. Sometimes I was getting notifications, sometimes not, but I could never get the userNotificationCenter(_:willPresent:completionHandler:) callback to to triggered.
It turned out there were two problems. The first I'm still a little confused by: my target deployment version was set to 11.0 but my project was set to 10.0. Changing the project to 11.0 was the first step. I don't fully understand this but maybe there is some difference in notification handling between 10.0 and 11.0?
The second part was the notification center delegate. I noticed Apple's note in the docs:-
Important
You must assign your delegate object to the UNUserNotificationCenter object before your app finishes launching. For example, in an iOS app, you must assign it in the application(:willFinishLaunchingWithOptions:) or application(:didFinishLaunchingWithOptions:) method of your app delegate. Assigning a delegate after these methods are called might cause you to miss incoming notifications.
I had been setting in a separate "notification manager" class, which is where the callbacks were also located (as delegate protocol implementations). I had instantiated this as an instance var in my app delegate, assuming this would be created early and not cause a problem.
I messed around with the instantiation etc for a while but only when I set the delegate in my application(_:didFinishLaunchingWithOptions:) method and implemented the delegate callbacks in the app delegate did I manage to fix it.
So my code became, basically:-
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// You MUST do this HERE and nowhere else!
UNUserNotificationCenter.current().delegate = self
// other stuff
return true
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// These delegate methods MUST live in App Delegate and nowhere else!
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
}
completionHandler(.alert)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
}
completionHandler()
}
}