If I run the following code in didFinishLaunchingWithOptions()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
Then the result is that didRegisterForRemoteNotificationsWithDeviceToken() gets called.
However if I change the code to be just:
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
Or as as its already running on main in this scenario, then just
application.registerForRemoteNotifications()
Then didRegisterForRemoteNotificationsWithDeviceToken() does NOT get called, but also neither does didFailToRegisterForRemoteNotificationsWithError().
Obtaining a push token is supposed to be independent of the user granting notifications permissions, so why am I not observing that behavior?
I only observe this behavior when running on hardware, when running on the simulator both forms of the code work. Yet its nothing to do with my phone not being able to contact the Apple servers etc. - if I change the code back and forth back and forth between the two then if 100% works when using requestAuthorization() and 100% doesn't when not using it.
There's nothing additional or out of the ordinary with the code, its standard app delete template stuff.
Why isn't it getting a push token when requestAuthorization() isn't used?
(I've tried adding an async delay to calling registerForRemoteNotifications(), but it made no difference).
This is expected behavior. If the app is not going to be able to do anything with a received push notification, then it will not be given a push token.
For a push token to be useful, the app has to either of:
- be authorized to show notifications for visible notifications
- be able to process the notifications in the background for silent notifications
Without neither of these, sent notifications will have no function, so the system decides to not serve a token.
Argun Tekant / DTS Engineer / Core Technologies