Getting Remote Notification Device Token in Swift 4?

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)
}

Working Code for getting deviceToken in - iOS 11 or greater,

Swift 4 | Swift 5

Request user permission

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

        // If granted comes true you can enabled features based on authorization.
        guard granted else { return }

        application.registerForRemoteNotifications()
    }        
    return true        
}

Getting device token

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print(token) 
}

In case of error

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

    print("i am not available in simulator :( \(error)")
}

Swift 5

You can use like,

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print(hexString)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var tokenString = ""

        for i in 0..<deviceToken.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }
                    print("tokenString: \(tokenString)")
}