Swift 3 - device tokens are now being parsed as '32BYTES'

前端 未结 11 2553
广开言路
广开言路 2020-12-13 01:27

I just updated from Xcode 7 to the 8 GM and amidst the Swift 3 compatibility issues I noticed that my device tokens have stopped working. They now only read \'32BYTES\'.

相关标签:
11条回答
  • 2020-12-13 01:43
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print(token)
    }
    
    0 讨论(0)
  • 2020-12-13 01:44

    The device token has never been a string and certainly not a UTF-8 encoded string. It's data. It's 32 bytes of opaque data.

    The only valid way to convert the opaque data into a string is to encode it - commonly through a base64 encoding.

    In Swift 3/iOS 10, simply use the Data base64EncodedString(options:) method.

    0 讨论(0)
  • 2020-12-13 01:52
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
        let token = deviceToken.map({ String(format: "%02.2hhx", $0)}).joined()
         print("TOKEN: " + token)
    
    
    }
    
    0 讨论(0)
  • 2020-12-13 01:53

    Get device token with proper format.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
    {
                var formattedToken = ""
                for i in 0..<deviceToken.count {
                    formattedToken = formattedToken + String(format: "%02.2hhx", arguments: [deviceToken[i]])
                }
                print(formattedToken)
    }
    
    0 讨论(0)
  • 2020-12-13 01:54

    Swift 3

    The best and easiest way.

    deviceToken.base64EncodedString()
    
    0 讨论(0)
  • 2020-12-13 01:55

    This one wasn't stated as an official answer (saw it in a comment), but is what I ultimately did to get my token back in order.

    let tokenData = deviceToken as NSData
    let token = tokenData.description
    
    // remove any characters once you have token string if needed
    token = token.replacingOccurrences(of: " ", with: "")
    token = token.replacingOccurrences(of: "<", with: ""
    token = token.replacingOccurrences(of: ">", with: "")
    
    0 讨论(0)
提交回复
热议问题