DEV Community

๐Ÿถ mono ๏ฃฟ
๐Ÿถ mono ๏ฃฟ

Posted on

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)