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

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

    For Swift :

    var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )
        var deviceTokenString: String = ( deviceToken.description as NSString )
        .stringByTrimmingCharactersInSet( characterSet )
        .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String
    
    println( deviceTokenString )
    
    0 讨论(0)
  • 2020-11-28 19:27

    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];
    }
    
    0 讨论(0)
  • 2020-11-28 19:27

    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 讨论(0)
  • 2020-11-28 19:29

    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
    0 讨论(0)
  • 2020-11-28 19:29

    What about one line solution?

    Objective C

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

    Swift

    let token = data.description.componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet).joinWithSeparator("")
    
    0 讨论(0)
  • 2020-11-28 19:30

    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();
    }
    
    0 讨论(0)
提交回复
热议问题