Skip to content

How To Get the Device Token in iOS

Apple Push Notification service (APNs) must know the address of a user’s device, aka device token, before it can send notifications to that device.

At launch time, your app communicates with APNs and receives its device token, which you then forward to your provider server. Your server includes that token with any notifications it sends.

1. Enable the Push Notifications Capability

Add Push Notifications capability in the Xcode Project > Main Target > Signing & Capabilities panel.

enable-push-notifcations-capability

2. Register Notifications With registerForRemoteNotifications method

You can all registerForRemoteNotifications() method of UIApplication to initiate the registration process with Apple Push Notification service.

swift
func application(_ application: UIApplication,
           didFinishLaunchingWithOptions launchOptions:
           [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
   // Override point for customization after application launch.
       
   UIApplication.shared.registerForRemoteNotifications()
   return true
}

3. Receive Device Token With didRegisterForRemoteNotificationsWithDeviceToken Method

If registration succeeds, the app calls your app delegate objects’s application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method and passes it a device token. You should pass this token along to the server you use to generate remote notificaion for the device.

swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {         
   let deviceTokenString = deviceToken.reduce("", { $0 + String(format: "%02X", $1) })
   print("deviceToken:\(deviceTokenString)")
   // upload device token to your app's push server
   self.sendDeviceTokenToServer(data: deviceToken)
}

If registration fails, the app calls its app delegate’s application(_:didFailToRegisterForRemoteNotificationsWithError:) method instead.

swift
func application(_ application: UIApplication,
           didFailToRegisterForRemoteNotificationsWithError 
               error: Error) {
   print("register remote notification error:\(error)")
  // Try again later.
}

4. Request Permissson to User Notifications (Optional)

If you want your app’s remote notification to display alerts, play sounds, or perform other user-facing actions, you must request authorization to do so using requestAuthorization(options:completionHandler:) method of UNUserNotificationCenter.

swift
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    
    if let error = error {
        // Handle the error here.
    }
    
    // Enable or disable features based on the authorization.
}

If you do not request and receive authorization for your app’s interactions, the system delivers all remote notifications to your app silently.

When does the Device Token Expire

If you install your app on a device, then get a device token by calling registerForRemoteNotifications method, the device token will not expire until the app was deleted on the device. It also doesn’t expire when your app updates to a new version or the iOS system reboots.

If you app has been deleted on a device, and then a notification is sent to the app once, then the previous device token will be marked as “not in use”.

APNs may start returning a "410 Unregistered" status for the token which has been determined to be no longer in use.

To avoid developers from detecting and tracking user behaviour around installations and uninstallations, APNs will start returning a "410 Unregistered" status on a fuzzy schedule which is not documented, and can change at any time.

Although the device token only expires when the app was deleted, Apple still suggest us never cache device tokens in local storage and we should get an up-to-date token each time you ask the system to provide the token. Because APNs will issue new a token in some special cases.

VoIP and Live Activity Device Tokens

VoIP and live activity push notifications have a different registering and receiving device token flow from the above standard push notifications.

VoIP Push Device Token

For VoIP push notifications, you need to use a different PushKit Framework to register and receive VoIP device token.

Please refer to Prepare Your App to Receive VoIP Push Notifications

Live Activity Push Device Token

Live activity has two kinds of device token, one is for updating the data of a exist live activity, the other is for starting a new live activity with a push notification.

Please refer to the following articles:


Have any questions? Feel free to drop me a message on Twitter!

References