DEV Community

🐶 mono 
🐶 mono 

Posted on

10 1

How to convert an APNs token to `String` from `Data`?

I think this is the best code to convert an APNs token to String from Data.

let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined()
Enter fullscreen mode Exit fullscreen mode

Usage

// Define initializer
extension String {
    public init(deviceToken: Data) {
        self = deviceToken.map { String(format: "%.2hhx", $0) }.joined()
    }
}

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data!) {
    // Use like this:
    let token = String(deviceToken: deviceToken)
}
Enter fullscreen mode Exit fullscreen mode

Full Japanese version: Swiftでプッシュ通知用のDevice Token(Data型)を16進数文字列へ変換する方法 - Qiita

Top comments (0)

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay