How can I convert my device token (NSData) into an NSString?

后端 未结 30 1928
挽巷
挽巷 2020-11-28 18:31

I am implementing push notifications. I\'d like to save my APNS Token as a String.

- (void)application:(UIApplication *)application
didRegisterForRemoteNotif         


        
30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 19:17

    Throwing my answer on the pile. Avoid using string parsing; It's not guaranteed by the docs that NSData.description will always work that way.

    Swift 3 Implementation:

    extension Data {
        func hexString() -> String {
            var bytesPointer: UnsafeBufferPointer = UnsafeBufferPointer(start: nil, count: 0)
            self.withUnsafeBytes { (bytes) in
                bytesPointer = UnsafeBufferPointer(start: UnsafePointer(bytes), count:self.count)
            }
            let hexBytes = bytesPointer.map { return String(format: "%02hhx", $0) }
            return hexBytes.joined()
        }
    }
    

提交回复
热议问题