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

后端 未结 30 2000
挽巷
挽巷 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:11

    Functional Swift version

    One liner:

    let hexString = UnsafeBufferPointer(start: UnsafePointer(data.bytes),
    count: data.length).map { String(format: "%02x", $0) }.joinWithSeparator("")
    

    Here's in a reusable and self documenting extension form:

    extension NSData {
        func base16EncodedString(uppercase uppercase: Bool = false) -> String {
            let buffer = UnsafeBufferPointer(start: UnsafePointer(self.bytes),
                                                    count: self.length)
            let hexFormat = uppercase ? "X" : "x"
            let formatString = "%02\(hexFormat)"
            let bytesAsHexStrings = buffer.map {
                String(format: formatString, $0)
            }
            return bytesAsHexStrings.joinWithSeparator("")
        }
    }
    

    Alternatively, use reduce("", combine: +) instead of joinWithSeparator("") to be seen as a functional master by your peers.


    Edit: I changed String($0, radix: 16) to String(format: "%02x", $0), because one digit numbers needed to having a padding zero

    (I don't know yet how to mark a question as a duplicate of this other one, so I just posted my answer again)

提交回复
热议问题