Getting Remote Notification Device Token in Swift 4?

Sandip Gill picture Sandip Gill · Nov 20, 2017 · Viewed 34.1k times · Source

I am using this code to get the Notification Center Device token.

It was working in Swift 3 but not working in Swift 4. What changed?

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {    
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenString)
}

Answer

Ahmad F picture Ahmad F · Nov 20, 2017

Assuming that you already checked that everything has been setup right, based on your code, it seems that it should works fine, all you have to do is to change the format to %02.2hhx instead of %02X to get the appropriate hex string. Thus you should get a valid one.

As a good practice, you could add a Data extension into your project for getting the string:

import Foundation

extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}

Usage:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString
    print(deviceTokenString)
}