Search code examples
iosswiftdevice

Cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer' in Swift5


I'm trying to get a device token.

  1. First of all, is this unique value?

    I recognize it as a unique value and try to get it. And I was following the way to get a device token when I saw an error.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes)  // get Error 
        var token = ""
        
        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", arguments: [chars[i]])
        }
        
        print("Registration succeeded!")
        print("Token: ", token)
    }

Error is Cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'

How can I remove this error?

And

  1. is this a value that won't change if you reinstall the app?

Solution

  • Since Swift 3 you can convert Data to a hex string much simpler

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
        let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
        print("Registration succeeded!")
        print("Token: ", token)
    }
    

    Your questions:

    1. Yes
    2. The value changes periodically. If you don't manage a server which sends push notifications you don't need to care about the token.