How to properly convert a binary push device token to a String

Formatting byte-by-byte into a sequence of hexadecimals

When you register your app with Apple’s push notification services, you will receive a device token in binary form, as a Data object. In order to pass this token to your backend, you’ll most likely need to convert it to a String first, but how? There’s no standard approach for this, after all. In the past, many have resorted to Data.description, but this has proven unwise, especially after Apple changed Data.description’s output with iOS 13.

Most of us have now settled on the following:

  • map over each binary byte
  • string format each byte as a 2-digit hexadecimal
  • join into a single string

In code:

func formatDeviceToken(_ token: Data) -> String {
  token.map { String(format: "%02.2hhx", $0) }.joined()
}

In case you’d like to read up on the topic in-depth, NSHipster wrote up a nice overview on handling push device tokens.