185

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

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
    NSString *tokenString = [NSString stringWithUTF8String:[newDeviceToken bytes]]; //[[NSString alloc]initWithData:newDeviceToken encoding:NSUTF8StringEncoding];
    NSLog(@"%@", tokenString);
    NSLog(@"%@", newDeviceToken);
}

The first line of code prints null. the second prints the token. How can I get my newDeviceToken as an NSString?

3

30 Answers 30

264

If anyone is looking for a way to do this in Swift:

Swift 3 introduces the Data type, with value semantics. To convert the deviceToken to a String, you can do as follows:

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

Old answer using NSData:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("tokenString: \(tokenString)")
}
14
  • 138
    Why does this have to be so complicated, what's wrong with the OS giving us a string since that is what everyone needs ? Thank you for this solution.
    – Piwaf
    Jun 19, 2015 at 18:28
  • 3
    @Sascha I hope you approve of my edit to your very useful answer :)
    – jrturton
    Jan 14, 2016 at 20:35
  • 16
    I refactored: let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() qiita.com/mono0926/items/3cf0dca3029f32f54a09
    – mono
    Sep 22, 2016 at 5:58
  • 2
    I don't recommend using .description as that is not guaranteed to be stable. Check out my answer here: stackoverflow.com/questions/9372815/… Sep 28, 2016 at 19:45
  • 10
    Can you explain what does "%02.2hhx do?
    – mfaani
    Nov 14, 2017 at 17:05
164

Someone Helped me with this.I am just passing along

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {

    const unsigned *tokenBytes = [deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                         ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                         ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                         ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

    [[MyModel sharedModel] setApnsToken:hexToken];
}
14
  • 5
    This is the best solution, since encondig bytes as hex, implies that you can count it ;) Sep 14, 2012 at 12:56
  • 4
    On XCode 5 I had to cast the deviceToken to make it compile: const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    – Ponytech
    Oct 6, 2013 at 21:15
  • 3
    Tokens are going to be larger than 32 bytes soon so this will need to be a loop over each byte, instead of eight hard-coded integers. Oct 28, 2015 at 4:56
  • 5
    Would this be a better solution? const unsigned *tokenBytes = [deviceToken bytes]; NSMutableString *hexToken = [NSMutableString string]; for (NSUInteger byteCount = 0; byteCount * 4 < [deviceToken length]; byteCount++) { [hexToken appendFormat:@"%08x", ntohl(tokenBytes[byteCount])]; }
    – Harro
    Mar 23, 2016 at 14:52
  • 9
    Important: APNs device tokens are of variable length. Do not hard-code their size. Apple says. Oct 18, 2016 at 1:56
154

You could use this

- (NSString *)stringWithDeviceToken:(NSData *)deviceToken {
    const char *data = [deviceToken bytes];
    NSMutableString *token = [NSMutableString string];

    for (NSUInteger i = 0; i < [deviceToken length]; i++) {
        [token appendFormat:@"%02.2hhX", data[i]];
    }

    return [token copy];
}
5
  • 11
    This should be the accepted answer, as it is way more safe than using description. Apr 24, 2015 at 10:12
  • 8
    This is the only correct answer in Objective-C that will handle the upcoming increase in the token size. Oct 28, 2015 at 5:17
  • Agreed that this is probably the safest way as it doesn't assume any particular token size/length.
    – Ryan H.
    Jun 30, 2016 at 21:56
  • Works in iOS 10.
    – Tjalsma
    Aug 2, 2017 at 1:41
  • 2
    I've used [token appendFormat:@"%02.2hhx", data[i]]; as Amazon SNS requires lower case. Jul 18, 2019 at 7:20
42

For those who want in Swift 3 and most easier method

func extractTokenFromData(deviceToken:Data) -> String {
    let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    return token.uppercased();
}
3
  • 1
    I wrote the same code :) This is most swifty version, and only this works
    – Quver
    Oct 10, 2016 at 20:14
  • 1
    @Anand can u please explain what is happing in this code deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) Apr 19, 2017 at 6:54
  • 1
    It uses reduce function of swift that serialises Data into hexadecimal string and then to String. To understand more about reduce function read useyourloaf.com/blog/swift-guide-to-map-filter-reduce
    – Anand
    Apr 19, 2017 at 13:11
33

Note - This will not work when compiling with the iOS 13 or later SDK

use this :

NSString * deviceTokenString = [[[[deviceToken description]
                         stringByReplacingOccurrencesOfString: @"<" withString: @""] 
                        stringByReplacingOccurrencesOfString: @">" withString: @""] 
                       stringByReplacingOccurrencesOfString: @" " withString: @""];
        
NSLog(@"The generated device token string is : %@",deviceTokenString);
16
  • 139
    It seems a bad idea to use description : nothing ensures that later version of iOS will not change the implementation and result of this call.
    – madewulf
    Nov 14, 2012 at 14:00
  • 18
    Indeed, this is a really bad idea. Sep 24, 2013 at 15:59
  • 21
    @madewulf very nice of you to point out how it's such a terrible idea to use description.. it would have been even nicer if you have suggested an alternative
    – abbood
    Jul 4, 2014 at 6:54
  • 6
    The solution here under with [deviceToken bytes] fits the bill.
    – madewulf
    Jul 31, 2014 at 15:30
  • 39
    Turns out as of Swift 3/iOS 10, .description on a device token returns "32 bytes". So yeah, don't use this. Sep 13, 2016 at 17:04
25

Explanation of %02.2hhx in the high vote answer:

  • %: Introduces the x conversion specifier.
  • 02: The minimum width of the converted value is 2. If the converted value has fewer bytes than the field width, it shall be padded with 0 on the left.
  • .2: Gives the minimum number of digits to appear for the x conversion specifier.
  • hh: Specifies that the x conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing).
  • x: The unsigned argument shall be converted to unsigned hexadecimal format in the style "dddd"; the letters "abcdef" are used. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.

For more details, see the IEEE printf specification.


Based on the above explanation, I think it is better to change %02.2hhx to %02x or %.2x.

For Swift 5, the following methods are all feasible:

deviceToken.map({String(format: "%02x", $0)}).joined()
deviceToken.map({String(format: "%.2x", $0)}).joined()
deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
deviceToken.reduce("", {$0 + String(format: "%.2x", $1)})

The test is as follows:

let deviceToken = (0..<32).reduce(Data(), {$0 + [$1]})
print(deviceToken.reduce("", {$0 + String(format: "%.2x", $1)}))
// Print content:
// 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
2
  • Thank you for this answer. Does this work also with iOS 12? Or does it only depend on Swift version?
    – Markus
    Jun 9, 2020 at 8:57
  • 1
    @Markus This works in iOS 12, only depends on Swift version.
    – jqgsninimo
    Jun 9, 2020 at 14:59
17

In iOS 13 the description will be in different format. Kindly use below code to fetch the device token.

- (NSString *)fetchDeviceToken:(NSData *)deviceToken {
    NSUInteger len = deviceToken.length;
    if (len == 0) {
        return nil;
    }
    const unsigned char *buffer = deviceToken.bytes;
    NSMutableString *hexString  = [NSMutableString stringWithCapacity:(len * 2)];
    for (int i = 0; i < len; ++i) {
        [hexString appendFormat:@"%02x", buffer[i]];
    }
    return [hexString copy];
}
2
  • Perfect solution for ios 13. Thanks Vishnu
    – Manish
    Nov 29, 2019 at 6:32
  • 1
    It doesn't compile currently - length in the for loop should be changed to len. Apparently a too small change for me to make an edit.. But else works perfectly! Dec 19, 2019 at 15:07
13

It's my solution and It works well in my app:

    NSString* newToken = [[[NSString stringWithFormat:@"%@",deviceToken] 
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""];
  • convert NSData to NSString with stringWithFormat
  • trim the "<>"
  • remove the spaces
6
  • 11
    This just implicitly calls -description, so it isn't any safer than the accepted answer.
    – jszumski
    Nov 10, 2014 at 20:59
  • Can you please link your source? I can't find information about it anywhere. Thx.
    – Zeb
    Nov 11, 2014 at 22:36
  • Found it! I think that it is a little different. Use the description attribute directly is not safe because it could change in future versions, but if you use it THROUGH a NSString method you will hardly have problems.
    – Zeb
    Nov 11, 2014 at 22:47
  • 6
    No this really calls description on deviceToken like jszumski says.
    – Jonny
    Mar 31, 2015 at 8:00
  • 1
    @Zeb It's not safe to rely on description whether you call it directly, or use it through another method, because the format of the returned string could be changed at any time. The correct solution is here: stackoverflow.com/a/16411517/108105 Oct 28, 2015 at 5:00
11

I think converting deviceToken to hex byte string has no sense. Why? You will send it to your backend, where it will be transformed back to bytes to be pushed to APNS. So, use NSData's method base64EncodedStringWithOptions, push it to server, and then use reverse base64decoded data :) That is so much easier :)

NSString *tokenString = [tokenData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
2
  • @jeet.chanchawat please do not add code to other users' answers. We don't want to put words in their mouth, especially when adding Swift to an Objective-C answer. Instead, add your own answer.
    – JAL
    Feb 6, 2017 at 15:27
  • 2
    I just didn't wanted to plagiarise the @Oleg Shanyuk's answer. As it is just the translation in another language built upon his answer, So he deserves the future up votes. If I add another answer it will give me upvotes for the answer which is research of someone else. Hope this justifies the EDIT. Feb 7, 2017 at 7:23
11

In iOS 13 description will break so use this

let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()

For clarity, let’s break this down and explain each part:

The map method operates on each element of a sequence. Because Data is a sequence of bytes in Swift, the passed closure is evaluated for each byte in deviceToken. The String(format:) initializer evaluates each byte in the data (represented by the anonymous parameter $0) using the %02x format specifier, to produce a zero-padded, 2-digit hexadecimal representation of the byte / 8-bit integer. After collecting each byte representation created by the map method, joined() concatenates each element into a single string.

P.S don't use description gives different string in iOS 12 and iOS 13 and not safe as per future scope. Developers shouldn’t have relied on a specific format for an object’s description.

// iOS 12
(deviceToken as NSData).description // "<965b251c 6cb1926d e3cb366f dfb16ddd e6b9086a 8a3cac9e 5f857679 376eab7C>"

// iOS 13
(deviceToken as NSData).description // "{length = 32, bytes = 0x965b251c 6cb1926d e3cb366f dfb16ddd ... 5f857679 376eab7c }"

For more information read This.

1
  • how to write this in javascript
    – Dhrupal
    Aug 15, 2020 at 10:50
6

2020

token as text...

let tat = deviceToken.map{ data in String(format: "%02.2hhx", data) }.joined()

or if you prefer

let tat2 = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()

(result is the same)

0
3

This is a little bit shorter solution:

NSData *token = // ...
const uint64_t *tokenBytes = token.bytes;
NSString *hex = [NSString stringWithFormat:@"%016llx%016llx%016llx%016llx",
                 ntohll(tokenBytes[0]), ntohll(tokenBytes[1]),
                 ntohll(tokenBytes[2]), ntohll(tokenBytes[3])];
3

Functional Swift version

One liner:

let hexString = UnsafeBufferPointer<UInt8>(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<UInt8>(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)

1
  • Works for me, Thanks.
    – Hasya
    Jun 15, 2016 at 13:41
2

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<UInt8> = UnsafeBufferPointer(start: nil, count: 0)
        self.withUnsafeBytes { (bytes) in
            bytesPointer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count:self.count)
        }
        let hexBytes = bytesPointer.map { return String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }
}
2

This will work for you,

NSUInteger dataLength = deviceToken.length;
    
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *deviceTokenString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
    [deviceTokenString appendFormat:@"%02x", dataBuffer[i]];
}
    
NSLog(@"The generated device token string is : %@",deviceTokenString);
1

I've tried to test two different methods with format "%02.2hhx" and "%02x"

    var i :Int = 0
    var j: Int = 0
    let e: Int = Int(1e4)
    let time = NSDate.timeIntervalSinceReferenceDate
    while i < e {
        _ =  deviceToken.map { String(format: "%02x", $0) }.joined()
        i += 1
    }
    let time2 = NSDate.timeIntervalSinceReferenceDate
    let delta = time2-time
    print(delta)

    let time3 = NSDate.timeIntervalSinceReferenceDate
    while j < e {
        _ =  deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
        j += 1
    }
    let time4 = NSDate.timeIntervalSinceReferenceDate
    let delta2 = time4-time3
    print(delta2)

and the result is that the fastest is "%02x" at average 2.0 vs 2.6 for the reduced version:

deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
1

Here's how you do it in Xamarin.iOS

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    var tokenStringBase64 = deviceToken.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
    //now you can store it for later use in local storage
}
1
  • I'm new to this but it looks like you need Hexadecimal when sending to APNS so I am not sure why you are suggesting base64...
    – Yepeekai
    Jun 23, 2022 at 19:49
1

Using updateAccumulatingResult is more efficient than the various other approaches found here, so here's the Swiftiest way to stringify your Data bytes:

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.reduce(into: "") { $0 += String(format: "%.2x", $1) }
    print(token)
}
1
  • Alex, wouldn't it be %02.2hhx
    – Fattie
    Mar 1, 2020 at 20:20
0

For Swift :

var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )
    var deviceTokenString: String = ( deviceToken.description as NSString )
    .stringByTrimmingCharactersInSet( characterSet )
    .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String

println( deviceTokenString )
-1
NSString *tokenString = [[newDeviceToken description] stringByReplacingOccurrencesOfString:@"[<> ]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [[newDeviceToken description] length])];
1
  • great solution As of today, it can be implified to credentials.token.description.replacingOccurrences(of: "[<> ]", with: "", options: .regularExpression, range: nil)
    – Frank
    Aug 14, 2016 at 0:41
-1

Swift:

let tokenString = deviceToken.description.stringByReplacingOccurrencesOfString("[ <>]", withString: "", options: .RegularExpressionSearch, range: nil)
-1

What about one line solution?

Objective C

NSString *token = [[data.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:@""];

Swift

let token = data.description.components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
1
  • 3
    This is the simple and the best solution. Thanks
    – Emmy
    Mar 26, 2016 at 18:06
-2
-(NSString *)deviceTokenWithData:(NSData *)data
{
    NSString *deviceToken = [[data description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    return deviceToken;
}
-2

Swift

    // make sure that we have token for the devie on the App
    func application(application: UIApplication
        , didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

            var tokenStr = deviceToken.description
            tokenStr = tokenStr.stringByReplacingOccurrencesOfString("<", withString: "", options: [], range: nil)
            tokenStr = tokenStr.stringByReplacingOccurrencesOfString(">", withString: "", options: [], range: nil)
            tokenStr = tokenStr.stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)



            print("my token is: \(tokenStr)")

    }
-2

Use excellent category!

// .h file

@interface NSData (DeviceToken)

- (NSString *)stringDeviceToken;

@end    

// .m file

#import "NSData+DeviceToken.h"

@implementation NSData (DeviceToken)

- (NSString *)stringDeviceToken {
    const unsigned *deviceTokenBytes = [deviceToken bytes];
    NSString *deviceToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                     ntohl(deviceTokenBytes[0]), ntohl(deviceTokenBytes[1]), ntohl(deviceTokenBytes[2]),
                     ntohl(deviceTokenBytes[3]), ntohl(deviceTokenBytes[4]), ntohl(deviceTokenBytes[5]),
                     ntohl(deviceTokenBytes[6]), ntohl(deviceTokenBytes[7])];
    return deviceToken;
}

@end

// AppDelegate.m

#import "NSData+DeviceToken.h"

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *token = deviceToken.stringDeviceToken;
}

Works fine!

1
  • Do not rely on using "description", it's format could change in the future. It is for display purposes only. May 25, 2016 at 3:39
-3

Swift 3:

If any one is looking for a way to get device token in Swift 3. Use the below modified snippet.

    let characterSet: CharacterSet = CharacterSet( charactersIn: "<>" )

    let deviceTokenString: String = (deviceToken.description as NSString)
        .trimmingCharacters(in: characterSet as CharacterSet)
        .replacingOccurrences(of: " ", with: "")
        .uppercased()

    print(deviceTokenString)
1
-4
var token: String = ""
for i in 0..<deviceToken.count {
    token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}

print(token)
1
  • 2
    Using description is not safe as it is not guaranteed to give same results in future. Oct 28, 2016 at 10:19
-4

The solution @kulss posted here, while lacking in elegance but having the virtue of simplicity no longer works in iOS 13, since description will work differently for NSData. You can still use debugDescription though.

NSString * deviceTokenString = [[[[deviceToken debugDescription]
                     stringByReplacingOccurrencesOfString: @"<" withString: @""] 
                    stringByReplacingOccurrencesOfString: @">" withString: @""] 
                   stringByReplacingOccurrencesOfString: @" " withString: @""];
-7

Try this one unless the data is null-terminated.

NSString* newStr = [[NSString alloc] initWithData:newDeviceToken encoding:NSUTF8StringEncoding];

2
-9
NSString *tokenstring = [[NSString alloc] initWithData:token encoding:NSUTF8StringEncoding];
1
  • This works when the data is a string, however, the deviceToken isn't a string. Aug 9, 2012 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.