Get the push notification token - iOS 10, Swift 3

后端 未结 9 824
深忆病人
深忆病人 2020-12-25 14:07

How to get the device token from new xCode 8, Swift 3 in iOS 10?

Here is the code to register notification:

<
相关标签:
9条回答
  • 2020-12-25 14:43

    Faced the same problem, this is the only thing that helped me:

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = String(format: "%@", deviceToken as CVarArg)
            .trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
            .replacingOccurrences(of: " ", with: "")
    }
    
    0 讨论(0)
  • 2020-12-25 14:43

    Code from Mixpanel library

        let tokenChars = (deviceToken as NSData).bytes.assumingMemoryBound(to: CChar.self)
        var tokenString = ""
        for i in 0..<deviceToken.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }
    
    0 讨论(0)
  • 2020-12-25 14:44

    One line:

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

    From this tutorial.

    Or a modular/encapsulated/OOP way:

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

    Then you can do this:

    let token = deviceToken.string
    
    0 讨论(0)
  • 2020-12-25 14:48

    It could work:

    let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes.assumingMemoryBound(to:CChar.self))
    

    Thanks!

    0 讨论(0)
  • 2020-12-25 14:49

    This method may solve your problem in iOS 10 and greater:

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

    The below snnipet is working with Eric Aya solution :

    let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    

    Thanks for all help :)

    0 讨论(0)
提交回复
热议问题