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)