跪拜 Guibai
← Back to the summary

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 requestAuthorization and registerForRemoteNotifications, 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:

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 didRegisterForRemoteNotificationsWithDeviceToken is that you actively called registerForRemoteNotifications.

If the user authorized a long time ago and the permission has been allowed ever since, as long as your code did not call registerForRemoteNotifications this 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:

2.2 Why tokens change

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:

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"
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

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:

  1. It is a normal remote notification or local notification (silent push doesn't go here);
  2. granted = YES;
  3. The app is currently in the foreground Active;
  4. 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:

  1. App in background suspended, user taps the notification banner;
  2. App killed, user taps notification to cold start;
  3. App in foreground, willPresent chose 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)

  1. Cold start: configure UNUserNotificationCenter.delegate, don't proactively request permission;
  2. At an appropriate business point (login success, entering the messages page, order completion), show your own soft prompt explaining "why push and what content";
  3. After the user agrees, call requestAuthorization to show the system dialog;
  4. In the completionHandler, whether granted is YES or NO, call registerForRemoteNotifications to 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

  1. When the didRegister callback 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;
  2. Bind again in the login-success callback. This is a fallback, because didRegister may happen before login, when there is no uid;
  3. When the token changes, upload the new token immediately; the backend uses the latest value;
  4. 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:

  1. User taps logout → call backend unbindToken(token), which clears or deletes the mapping for that token's uid;
  2. Client clears the in-memory uid, keeps the token string (device unchanged, token unchanged);
  3. New account logs in → call bindToken(newUid, token) with the current token.

Two traps to avoid:

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

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:

  1. 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.
  2. Treating the token as a permanent constant cached locally. Wrong. The token changes; upload it on every didRegister.
  3. Using unregisterForRemoteNotifications to unbind an account. Wrong. That also deregisters the APNs registration entirely.
  4. One token bound to two uids simultaneously. That's the source of cross-account message leakage. The server must enforce a unique constraint.
  5. Updating UI directly inside didRegister. It's asynchronous and off the main thread.
  6. Treating silent push as an IM message channel. Throttling + won't wake after force-quit; it's unreliable.
  7. Sending sandbox tokens to production. The symptom is "works in development, silently fails in production"; you must separate env in the table.
  8. Removing registerForRemoteNotifications from startup logic. Even with permissions on, you won't get a token, and push goes completely silent with no easy way to diagnose.
  9. Using willPresent as the unified "received push" entry. It only fires when the app is foreground + granted=YES + normal notification.
  10. 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:

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.