iOS Push: Why Your DeviceToken Isn't the Same as Notification Permission
iOS Remote Push Full-Stack Breakdown: From deviceToken to Multi-Account Binding
This is a summary I put together after thoroughly sorting out the pitfalls I repeatedly hit when implementing push for an IM-style app with an account system: "notification authorization", "APNs registration", and "token binding". Many articles online conflate
requestAuthorizationandregisterForRemoteNotifications, which makes all subsequent reasoning wrong. Here I break things down by the boundaries of the mechanisms themselves. Code is primarily Objective-C, minimum deployment iOS 13.
1. First, separate the two systems: the root of all confusion
The most common mistake beginners make is thinking "user authorizes notifications → the system automatically gives me a deviceToken." In fact, Apple designed two independent mechanisms for this.
1.1 UNUserNotificationCenter: only manages "whether to display"
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
// granted decides whether the system should display when a notification arrives
}];
Its responsibilities are very clear:
- Controls banners, sound, badges, Notification Center list, Lock screen display;
- Does not access APNs servers, does not generate or return a deviceToken;
- The authorization result is stored in the system; the entry point is "Settings → Your App → Notifications";
- The system authorization dialog appears only once per app install lifecycle. The first call shows the dialog; subsequent calls just return the saved state and do not show it again.
So it is essentially a "display switch", not a "push channel switch". If you don't establish this first, all subsequent reasoning goes wrong.
1.2 UIApplication.registerForRemoteNotifications: the real entry to APNs
[[UIApplication sharedApplication] registerForRemoteNotifications];
Calling this makes the system framework actually register with Apple's APNs servers, negotiating the unique identifier for this device + this app (bundleId) + this environment (sandbox / production), which is the deviceToken. Results are returned via two AppDelegate callbacks:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
Key conclusion worth remembering separately:
The only trigger for
didRegisterForRemoteNotificationsWithDeviceTokenis that you actively calledregisterForRemoteNotifications.
If the user authorized a long time ago and the permission has been allowed ever since, as long as your code did not call
registerForRemoteNotificationsthis time, the callback will never fire and you will never get a token.
Also, this registration process does not check notification authorization status. The user can tap "Don't Allow" and you can still call registerForRemoteNotifications and successfully get a deviceToken; subsequent push just won't display, only silently delivered.
1.3 The actual effect of the four combinations
Taking the Cartesian product of the two switches, the behavior and effect are:
| Scenario | Ask Authorization | granted | Call register | Can get token | Push effect |
|---|---|---|---|---|---|
| A | Yes | YES | Called | Yes | Normal banner, sound, badge |
| B | Yes | NO | Called | Yes | Only silent delivery, no visible alert |
| C | Never asked | Default NO | Called | Yes | Same as above, silent delivery |
| D | Yes | YES | Not called | Cannot get, callback won't fire | Backend has no token, can't push |
D is the row most likely to cause production incidents: during an update, someone removes registerForRemoteNotifications from the startup logic. Permissions are still on, but the new version never gets a token to send to the backend, and push goes completely silent.
2. deviceToken lifecycle
2.1 What the system does after you call it
registerForRemoteNotifications
│
▼
System framework connects to APNs (HTTPS, asynchronous, not main thread)
│
├── APNs already has a valid token → quickly returns old token, callback didRegister
├── No valid token (new install / reinstall / erase / Apple rotation) → generates new token, callback didRegister
└── Network unreachable, certificate mismatch, environment mismatch → goes to didFail
Note two things:
- The callback is asynchronous and not on the main thread. If you update UI or need main-thread stuff, you must switch back to the main queue.
- Calling it multiple times is safe and officially recommended. Apple's documentation explicitly recommends calling
registerForRemoteNotificationsat every app launch. Don't treat the token as a permanent constant. The system has a cache, so if the token hasn't changed, the callback is fast and doesn't rerun the whole negotiation.
2.2 Why tokens change
- App uninstall and reinstall;
- Erase all content / restore;
- Restoring from a backup to another device;
- Apple's APNs backend rotation policy (not announced to developers, happens from time to time).
When a token changes, the old token in your backend is dead data. So every didRegister callback must send the current token to the backend, not just "send once at login."
2.3 Converting NSData to hex
The deviceToken is NSData. Directly using description or converting to UTF-8 gives garbage with angle brackets and spaces. You must convert byte-by-byte to a lowercase hex string:
- (NSString *)hexStringFromDeviceToken:(NSData *)data {
const uint8_t *bytes = data.bytes;
NSMutableString *hex = [NSMutableString stringWithCapacity:data.length * 2];
for (NSUInteger i = 0; i < data.length; i++) {
[hex appendFormat:@"%02x", bytes[i]];
}
return [hex copy];
}
3. Payload decides the delivery path: normal notifications vs silent push
When APNs receives a push from your backend, the first thing it does is not deliver but check if the aps dictionary has content-available: 1. This one field splits push into two completely independent paths.
3.1 Normal remote notifications
{
"aps": {
"alert": { "title": "Title", "body": "Content" },
"sound": "default",
"badge": 1
}
}
This kind of push means "a notification card for the user to see", so it strongly depends on notification authorization:
granted = YES: goes to UNUserNotificationCenter, through the notification delegate system;granted = NO: the system directly discards the message and does not deliver it to the app.
There is a common hope that "I won't show a banner, but when the app is in the foreground, I can secretly run some code." Normal notifications cannot do that. When the user denies authorization, the message is consumed at the system level. willPresentNotification doesn't fire, didReceiveNotificationResponse doesn't fire, didReceiveRemoteNotification:fetchCompletionHandler: doesn't fire. The app has no way to know the push ever arrived.
3.2 Silent push (Background Notification)
{
"aps": { "content-available": 1 },
"sync": "pull_unread"
}
- Does not depend on notification authorization. Whether granted is YES or NO, it can be attempted for delivery;
- Does not produce any notification card. No Lock screen, Notification Center, banner, sound, or badge. The user is completely unaware; that's what "silent" means;
- Does not go through the UN notification delegate.
willPresentanddidReceiveResponseare not called; - The only callback entry is AppDelegate:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;
- Usage: wake the app in the background, give about 30 seconds to sync data, pull unread, preload, update configuration;
- Prerequisite: the project must enable
Signing & Capabilities → Background Modes → Remote notifications, otherwise it won't receive; - Hard limitation: the system does throttling, deciding based on battery, network, and user usage patterns. If the user has force-quit the app, silent push probably won't wake it (varies slightly by OS version).
So silent push cannot be treated as a reliable message channel. For IM-style apps that want guaranteed delivery, you must steer the user toward normal notifications with authorization. Silent push can only be a supplementary synchronization method for foreground/background states.
3.3 Comparison of the two paths
| Push type | Key aps field | Can reach app with granted=NO | Callback entry | Has notification card |
|---|---|---|---|---|
| Normal remote notification | alert / sound / badge | No, system directly discards | willPresent / didReceiveResponse | Yes |
| Silent push | content-available: 1 |
Yes (subject to background policy) | didReceiveRemoteNotification:fetchCompletionHandler: |
No |
| Local notification | UNNotificationRequest, not via APNs | Requires granted=YES | willPresent / didReceiveResponse | Yes |
One more often-ignored point: the permission switch does not change the deviceToken. The same token, if the user later enables notifications in system settings, immediately gets banner capability. Turning it off makes it silent again. No need to re-register, and no new token. The token identifies "device + App + environment"; the permission controls "whether the system displays".
4. Trigger conditions for the four delegate methods
Push callbacks are easy to mix up. Let's nail down "when does each get called".
4.1 willPresentNotification:withCompletionHandler:
Called when the app is in the foreground Active and receives a notification card.
Required conditions, all must be true:
- It is a normal remote notification or local notification (silent push doesn't go here);
granted = YES;- The app is currently in the foreground Active;
- APNs successfully delivered the notification to UNUserNotificationCenter.
Its purpose is practical: foreground doesn't show banners by default; here you decide whether to display this time:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
// In foreground, also show banner, play sound, update badge
completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
}
Not called when: granted=NO (message blocked by system), app in background (system directly shows banner, doesn't call this), silent push, or app killed.
4.2 didReceiveNotificationResponse:withCompletionHandler:
Called only when the user actively taps the notification card.
Scenarios:
- App in background suspended, user taps the notification banner;
- App killed, user taps notification to cold start;
- App in foreground,
willPresentchose to show banner, and user taps that foreground banner.
Not called when: notification delivered but user didn't tap (ignored); normal push with granted=NO (there's no card to tap); silent push (no card).
So to correct a common statement: it's not "foreground tap / background tap / cold-start tap" as three separate scenarios; the common precondition for all is "the user tapped a notification card". Delivery itself doesn't enter this delegate, which is why many "read receipt" implementations are wrong.
4.3 didReceiveRemoteNotification:fetchCompletionHandler:
This is the background callback entry for silent push (and for normal pushes that contain content-available: 1). For silent push it's the only entry. You must call UIBackgroundFetchResult in the completionHandler, otherwise the system will think your background task didn't finish, which affects future wake priority.
4.4 didFailToRegisterForRemoteNotificationsWithError:
The registration failure callback. Common causes: network unavailable, push certificate / App ID capability not enabled, using a production certificate in development (or vice versa), device not supported. In production, log/report here; otherwise silent push failures are hard to diagnose.
5. When to ask for notification permission
Apple's advice is clear: don't pop the system authorization dialog as soon as the app launches. The system dialog is a one-time opportunity per install lifecycle; if the user taps "Don't Allow" casually, you permanently lose that channel.
5.1 Recommended flow (for apps with an account system)
- Cold start: configure
UNUserNotificationCenter.delegate, don't proactively request permission; - At an appropriate business point (login success, entering the messages page, order completion), show your own soft prompt explaining "why push and what content";
- After the user agrees, call
requestAuthorizationto show the system dialog; - In the completionHandler, whether granted is YES or NO, call
registerForRemoteNotificationsto get the token.
- (void)requestPushPermissionIfNeeded {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
// If already explicitly denied or authorized, don't bother the user again
if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}];
} else {
// Already authorized / denied, still register to keep token valid
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}
}];
}
The advantage of authorizing first and then registering: the moment you get the token, push already has banner capability, no need to wait for the next authorization.
The reverse order (register first, then ask authorization) technically works (you get the token immediately), but messages sent during that period are silent only, which is a poor product experience.
5.2 Provisional authorization (iOS 12+)
UNAuthorizationOptionProvisional
No system dialog. Notifications are quietly delivered to Notification Center, and the user chooses "Keep Quiet / Deliver Immediately / Off" from the notification itself. Suitable for products that don't want to burn the single dialog opportunity; conversion rates are usually higher than hard dialogs.
5.3 Fallback after permission denied
Don't repeatedly show the dialog after denial (it won't show; you're just calling an interface for nothing). The correct approach: add a guide in the in-app settings page, check settings.authorizationStatus, and if it's UNAuthorizationStatusDenied, guide the user to the system settings to enable it manually (UIApplicationOpenSettingsURLString). Once the user enables it in system settings, no app restart and no re-registration is needed; the original token becomes valid immediately.
6. How to bind/unbind tokens under an account system
This is the highest business-risk part of the whole design. The core rule is only one:
The same deviceToken (same device) should belong to only one logged-in account at any time. One uid can have multiple tokens (multi-device login), but one token cannot belong to multiple uids at the same time.
Otherwise, after switching accounts, A's messages will be pushed to the device now logged in as B, which is a clear cross-account incident.
6.1 Upload timing
- When the
didRegistercallback returns a token, upload it, but first check whether the user is logged in:- Logged in → directly call
bindToken(uid, token); - Not logged in → store the token in memory and locally, do not upload and bind to an anonymous uid;
- Logged in → directly call
- Bind again in the login-success callback. This is a fallback, because
didRegistermay happen before login, when there is no uid; - When the token changes, upload the new token immediately; the backend uses the latest value;
- No need to blindly upload at every launch, but every launch you must call
registerForRemoteNotifications— the callback then naturally leads to upload according to rules 1 and 2.
6.2 Logout / account switching
Correct sequence:
- User taps logout → call backend
unbindToken(token), which clears or deletes the mapping for that token's uid; - Client clears the in-memory uid, keeps the token string (device unchanged, token unchanged);
- New account logs in → call
bindToken(newUid, token)with the current token.
Two traps to avoid:
- Don't use
unregisterForRemoteNotificationsas an unbind. That API completely deregisters from APNs; after that you'll never get a token again. It should only be used when the user actively disables push or deletes their account. - Don't rely solely on client-side unbind. The client might crash or fail on network. The backend binding interface should be idempotent and mutually exclusive: use deviceToken as the unique key; a new binding automatically kicks off the old uid. Even if the client misses the unbind call, the server won't cross-account.
6.3 Suggested backend table structure
push_binding
uid bigint
device_token varchar(64) unique index
platform varchar(16) ios/android
bundle_id varchar(64)
env varchar(16) sandbox / production
updated_at timestamp
- Unique index on
device_tokenenforces "one device belongs to one account" at the database level; - Record
envto avoid sending sandbox tokens to the production channel (the most typical newbie mistake: "works locally, doesn't receive in production"); - Periodically clean invalid tokens using APNs Feedback / push receipts; don't let them sit in the table forever.
6.4 Complete sequence
App cold start
├── Configure UNUserNotificationCenter.delegate
├── Call registerForRemoteNotifications
│ └── didRegister callback
│ ├── Logged in → bindToken(uid, token)
│ └── Not logged in → cache token locally, don't upload
└── Ask authorization at business time (soft prompt → system dialog)
└── Call register again in completionHandler (to keep token valid)
Guest → Login
└── Login success → get current token → bindToken(uid, token)
(If no token yet, register once, then bind in callback)
Logged in → each launch
└── register → didRegister → bindToken (backend idempotent override)
Logout / switch account
└── unbindToken(token) → clear uid, keep token → new account login → bindToken
Apple rotates token
└── didRegister receives new token
├── Logged in → bind new token (backend overrides old value)
└── Not logged in → update local cache
7. Pitfall checklist
Ordered by how often I actually encountered them:
- Thinking that a denied permission means you can't get a deviceToken. Wrong. Denial only affects whether it can display; you still get the token.
- Treating the token as a permanent constant cached locally. Wrong. The token changes; upload it on every
didRegister. - Using
unregisterForRemoteNotificationsto unbind an account. Wrong. That also deregisters the APNs registration entirely. - One token bound to two uids simultaneously. That's the source of cross-account message leakage. The server must enforce a unique constraint.
- Updating UI directly inside
didRegister. It's asynchronous and off the main thread. - Treating silent push as an IM message channel. Throttling + won't wake after force-quit; it's unreliable.
- Sending sandbox tokens to production. The symptom is "works in development, silently fails in production"; you must separate env in the table.
- Removing
registerForRemoteNotificationsfrom startup logic. Even with permissions on, you won't get a token, and push goes completely silent with no easy way to diagnose. - Using
willPresentas the unified "received push" entry. It only fires when the app is foreground + granted=YES + normal notification. - Updating the app but not updating the push certificate / not enabling Push Notifications capability in App ID. Goes to
didFail; recommend logging/reporting.
8. Ready-to-use code skeleton
// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
// Register at every launch to keep token valid (independent of authorization)
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
#pragma mark - APNs registration result
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [self hexStringFromDeviceToken:deviceToken];
[PushManager sharedManager].currentDeviceToken = token;
if ([UserManager sharedManager].isLogin) {
[[PushManager sharedManager] bindToken:token uid:[UserManager sharedManager].uid];
}
// Not logged in: just cache, bind after login success
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"[Push] APNs registration failed: %@", error);
// Log/report in production
}
#pragma mark - Silent push
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Only silent push with content-available:1 enters here
[[PushManager sharedManager] syncFromRemotePayload:userInfo completionHandler:completionHandler];
}
#pragma mark - UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
// Foreground receives normal/local notification
completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
// User tapped the notification card (foreground/background/cold start)
[[PushManager sharedManager] handleNotificationTap:response.notification.request.content.userInfo];
completionHandler();
}
// PushManager.m —— bind / unbind
- (void)bindToken:(NSString *)token uid:(NSString *)uid {
if (token.length == 0 || uid.length == 0) return;
// Backend guarantees: device_token unique, new binding overrides old uid
[[APIClient sharedClient] bindPushToken:token uid:uid completion:nil];
}
- (void)unbindToken:(NSString *)token {
if (token.length == 0) return;
[[APIClient sharedClient] unbindPushToken:token completion:nil];
}
// Called after login success
- (void)handleLoginSuccessWithUid:(NSString *)uid {
NSString *token = [PushManager sharedManager].currentDeviceToken;
if (token.length > 0) {
[[PushManager sharedManager] bindToken:token uid:uid];
} else {
[[UIApplication sharedApplication] registerForRemoteNotifications];
// The callback will bind because isLogin is already YES
}
}
// Logout
- (void)handleLogout {
[[PushManager sharedManager] unbindToken:[PushManager sharedManager].currentDeviceToken];
[[UserManager sharedManager] clearUser]; // keep token
}
9. Self-test checklist
Before release / every time you change push-related code, run through this:
- Reinstall, cold start, confirm
didRegisterfires and token uploaded; - Choose "Don't Allow", confirm you still get a token, and silent push (
content-available:1) entersdidReceiveRemoteNotification; - With permission allowed, app foreground receives normal push, confirm
willPresentfires and banner shows as expected; - App background taps notification, confirm
didReceiveNotificationResponsefires and navigation params are correct; - Force-quit app, tap notification to cold start, confirm same and business params are not lost;
- Login A → logout → login B, trigger a push using A's business, confirm B's device does not receive it;
- Manually disable notification permission in system settings, confirm token unchanged and silent push still delivers;
- Disconnect network before forcing
registerForRemoteNotifications, confirmdidFailhas logs to look at.
Conclusion
The complexity of this mechanism essentially comes from Apple separating the "channel" and "display" into two independent subsystems: registerForRemoteNotifications handles the channel (token), and requestAuthorization handles display (banner). Once you understand this dividing line, the rest — callback trigger conditions, silent push boundaries, multi-account binding — are natural consequences of that line, not a pile of special cases to memorize.