Getting Remote Notification Device Token in Swift 4?

前端 未结 8 2357
梦谈多话
梦谈多话 2021-02-20 06:59

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 1         


        
8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 07:26

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

提交回复
热议问题