Swift 3
device tokens
32BYTES
iOS development
parsing changes

Swift 3 - device tokens are now being parsed as '32BYTES'

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift 3 and later, APNs device token handling moved away from string-description hacks to explicit byte conversion. Many old snippets broke because they parsed token text representation instead of raw Data. The reliable approach is to convert bytes to hex deterministically and keep environment handling explicit.

Why Legacy Parsing Broke

Older code often did this:

  • call deviceToken.description
  • remove angle brackets and spaces
  • send resulting string to backend

That approach depended on undocumented formatting details and failed across Swift and SDK changes. Device token should be treated as bytes, not formatted debug text.

Correct Device Token Conversion

Use byte-to-hex conversion directly from Data.

swift
1import UIKit
2
3func application(
4    _ application: UIApplication,
5    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
6) {
7    let token = deviceToken.map { String(format: "%02x", $0) }.joined()
8    print("APNs token: \(token)")
9}

This gives a stable lowercase hex string suitable for backend registration.

Token Lifecycle: Not Just Formatting

Formatting fix is only one part. Tokens can change after:

  • app reinstall
  • device restore
  • OS upgrade
  • APNs environment change

Update backend registration whenever token changes.

swift
1let storageKey = "apns_token"
2let defaults = UserDefaults.standard
3
4func updateTokenIfNeeded(_ token: String) {
5    let old = defaults.string(forKey: storageKey)
6    guard old != token else { return }
7    defaults.set(token, forKey: storageKey)
8    // send token to backend here
9}

Deduplicating updates reduces unnecessary network calls.

Sandbox and Production Environment Separation

APNs tokens differ between sandbox and production environments. Sending a sandbox token to production push provider causes delivery failures.

Keep environment metadata with token registration payload:

json
1{
2  "platform": "ios",
3  "push_env": "sandbox",
4  "token": "hex-token-value"
5}

Backend should route token to matching APNs endpoint.

Modern App Delegate and Scene Considerations

In current app architectures, remote notification registration still flows through app delegate callbacks even with scene-based lifecycle. Ensure delegate is configured and registration occurs after permission request.

swift
1import UserNotifications
2
3UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
4    guard granted, error == nil else { return }
5    DispatchQueue.main.async {
6        UIApplication.shared.registerForRemoteNotifications()
7    }
8}

Then process token in didRegisterForRemoteNotificationsWithDeviceToken.

Debugging Delivery Issues

When pushes fail, validate full chain:

  1. app receives token and logs conversion.
  2. backend receives and stores latest token.
  3. correct environment used for send.
  4. APNs provider response checked and logged.

APNs error feedback is essential for identifying expired or invalid tokens.

Backend Contract Design

Keep token registration API explicit so app and backend stay aligned. Useful fields include app version, environment, locale, and user association.

Example payload shape:

json
1{
2  "token": "hex-token-value",
3  "platform": "ios",
4  "environment": "production",
5  "app_version": "1.8.0",
6  "user_id": "u_12345"
7}

With this contract, backend teams can audit token churn and troubleshoot failed sends faster.

Test Matrix for Token Handling

Include these scenarios in QA:

  • fresh install and first permission prompt
  • permission denied then later enabled in settings
  • user logout and different user login on same device
  • app upgrade across major iOS versions

A small test matrix catches most lifecycle bugs before release.

Common Pitfalls

  • Parsing deviceToken.description instead of converting bytes.
  • Assuming token never changes after first registration.
  • Mixing sandbox and production tokens in same backend flow.
  • Registering token before notification permission handling is complete.
  • Ignoring provider error responses during push sends.

Summary

  • Treat APNs device token as raw bytes and convert to hex directly.
  • Avoid legacy string cleaning patterns tied to debug formatting.
  • Update backend only when token changes.
  • Track APNs environment with each token registration.
  • Validate end-to-end delivery path, not just client conversion code.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.