In UIKit, how does an iOS app register with APNs for a device token, and what should it do with that token on every launch?
answer
- UIApplication, not the notification center
- two app delegate callbacks
- variable-length Data, sent as hex
- never cached; new after restore or reinstall
- aps-environment: development or production
basics
~10 sCall UIApplication's registerForRemoteNotifications() on every launch; APNs answers in application(_:didRegisterForRemoteNotificationsWithDeviceToken:) with a Data token that the app hex-encodes and sends to its server, or in didFailToRegisterForRemoteNotificationsWithError.
solid answer
~40 sRegistration belongs to UIKit: `UIApplication.shared.registerForRemoteNotifications()`, called on each launch once the Push Notifications capability has added the `aps-environment` entitlement. Success arrives in `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` as `Data`; I hex-encode the bytes without assuming a length and send them, with the signed-in account, to our server, which passes them back to APNs unmodified. Failure arrives in `application(_:didFailToRegisterForRemoteNotificationsWithError:)` (no network, APNs unreachable, a missing entitlement) and I retry later. I never cache the token: APNs issues a new one after a restore from backup, on a new device or after an OS reinstall, and asking again is quick when nothing changed. Registering needs no permission prompt; without `requestAuthorization`, pushes still arrive but silently. A development-signed debug build gets a token for APNs's development environment, so our server must send it through the development server, not production.
code
swift · 25 linesimport UIKit
func uploadPushToken(_ hex: String) async { /* POST to the app's own server */ }
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Every launch: the token may have changed, and asking again is cheap.
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Variable-length bytes, sent as hex; never sliced to a fixed size or cached.
let hex = deviceToken.map { String(format: "%02x", $0) }.joined()
Task { await uploadPushToken(hex) }
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
// No network, APNs unreachable or a missing aps-environment entitlement: retry later.
print("APNs registration failed:", error.localizedDescription)
}
}go deeper
Recall that UIApplication registers, the app delegate gets the token or an error, and the token goes to the app's server.
Explain why registration runs every launch, why the token is hex-encoded without a fixed length, and how registration differs from asking permission.
Diagnose missing pushes from the app side: a missing entitlement in the failure callback, a cached stale token, or a development token sent to production.
Decide what the app reports with each token, such as environment and account, so the server can route, rotate and retire tokens without guesswork.
## Who does what A remote notification has four parties, and a lot of confusion comes from mixing them up: | Party | Its job | API or setting | |---|---|---| | UIKit | Registers the app with APNs and hands over the device token | `registerForRemoteNotifications()`, two app delegate callbacks | | UserNotifications | Asks the person whether pushes may alert, sound or badge | `requestAuthorization(options:)` | | Apple Push Notification service (APNs) | Issues the token and delivers pushes to the device | Development and production servers | | The app's own server | Stores tokens per account and sends pushes | Outside the app | The **device token** is the address of one app on one device. Apple's documentation is precise about its scope: a token is unique to both the device and the app, so two apps on the same phone each need their own, and a server can never reuse one app's token for another. ## Turning on the capability Before registration can succeed, the target needs the **Push Notifications** capability in Xcode, which adds the `aps-environment` entitlement, and the App ID in the developer account needs push enabled. Without the entitlement, registration cannot succeed: Apple lists a missing code-signing entitlement among the causes that send the app the failure callback instead of a token. ## Registering on every launch The sequence is short: 1. In `application(_:didFinishLaunchingWithOptions:)`, call `application.registerForRemoteNotifications()`. 2. On success, UIKit calls `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` with a `Data` value. 3. On failure, UIKit calls `application(_:didFailToRegisterForRemoteNotificationsWithError:)`; Apple lists no network connection, an unreachable APNs server and a missing code-signing entitlement as causes, and recommends setting a flag and trying again later. Registering is independent of permission. `registerForRemoteNotifications()` shows no prompt; if the app never receives authorization through `requestAuthorization(options:)`, the system still delivers its remote notifications, but silently. Apple's authorization page still asks apps to request authorization before registering with APNs, so the usual order is the permission request first, then registration, even though neither call depends on the other's result. ## Handling the token Apple's rules for the token are few and strict: - **Send it, don't store it.** Forward the token to your server each time you receive it, over an encrypted connection, together with whatever identifies the user. Apple says never to cache it locally: APNs issues a new token when a device is restored from a backup, when the app is installed on a new device and when the OS is reinstalled, and UIKit may even call the callback without a new registration call, for example at the first launch after a device is restored from another device's data. - **Treat it as bytes.** Tokens are of variable length, so code must not assume a size. The usual form for the server is lowercase hex, two digits per byte, and the server passes the token back to APNs unmodified. - **Register every launch.** If nothing changed, registration returns the same token quickly; if something did, the server learns the new one at once. - **Expect several per user.** A person with a phone and a tablet has two tokens, and the server keeps both against the account. What the server does when one person signs out and another signs in on the same phone is a design question covered with push delivery design. ## Development and production environments APNs runs two environments, and a token belongs to the one the build was signed for: | Build | `aps-environment` | Server that must send its pushes | |---|---|---| | Debug build run from Xcode with a development profile | `development` | `api.sandbox.push.apple.com` | | TestFlight and App Store builds | `production` | `api.push.apple.com` | A team that points its staging server at the production host and then tests with a debug build sees pushes vanish even though registration succeeded. The fix is on the sending side: keep the environment with each stored token and send through the matching server. The provider API itself is a server subject; on the app side, the lesson is to report enough with each token, such as the build type, for the server to pick correctly. ## Mistakes reviewers catch - Converting the token with a string initializer instead of hex-encoding each byte. - Registering once and caching the token in user defaults. - Expecting `registerForRemoteNotifications()` to show the permission alert. - Ignoring the failure callback, so a missing entitlement goes unnoticed until release.
- Why hex-encode the token instead of decoding it with String(data:encoding: .utf8)?The token is opaque binary data, not UTF-8 text, so decoding it as text fails or mangles it. Hex-encoding turns each byte into two characters the server can store and send back, and the code makes no assumption about the token's length, because Apple documents device tokens as variable length.
- Does registerForRemoteNotifications() show the notification permission alert?No. The alert comes only from UserNotifications' `requestAuthorization(options:)`. UIKit's registration just obtains the token; if the person never grants permission, remote notifications still reach the app but are delivered silently, without alerts, sounds or badges.
- Pushes reach TestFlight testers but never a debug build run from Xcode; what is wrong?The debug build carries the development `aps-environment`, so its token is a development-environment token, while the server sends everything through the production host. Store the environment with each token and send development tokens through the development server; the app code itself is usually fine.
- Cache the token in user defaults and skip registration on later launches.
- registerForRemoteNotifications() is what shows the permission alert.
- Device tokens are always 32 bytes, so a fixed-size buffer is safe.
- One device token serves every app a company ships on that phone.
- Debug and App Store builds share one APNs environment, so one server host works.