如何将我的设备令牌(NSData)转换为NSString?

187

我正在实现推送通知。我想将我的APNS令牌保存为字符串。

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

第一行代码打印null。第二行打印了token。如何将我的newDeviceToken作为NSString获取?


第二个 NSLog 的输出是什么,即打印 newDeviceToken 的那个? - rob mayoff
请勿重复:https://dev59.com/o3M_5IYBdhLWcg3wmkeu#35730103 - NiñoScript
do NOT use description - Fattie
31个回答

-1

有没有一行解决方案?

Objective C

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

快捷

let token = data.description.components(separatedBy: CharacterSet.alphanumerics.inverted).joined()

3
这是最简单、最好的解决方案。谢谢。 - Emmy

-1
NSString *tokenString = [[newDeviceToken description] stringByReplacingOccurrencesOfString:@"[<> ]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [[newDeviceToken description] length])];

伟大的解决方案:截至今天,它可以简化为credentials.token.description.replacingOccurrences(of: "[<> ]", with: "", options: .regularExpression, range: nil)。 - Frank

-1

Swift:

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

-2
请使用优秀的类别!
// .h文件
@interface NSData (DeviceToken)

- (NSString *)stringDeviceToken;

@end    

// .m文件

#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;
}

运行良好!


不要依赖于使用“描述”,它的格式可能会在未来发生变化。它仅用于显示目的。 - Michael Peterson

-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
-(NSString *)deviceTokenWithData:(NSData *)data
{
    NSString *deviceToken = [[data description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    return deviceToken;
}

-3

Swift 3:

如果有人正在寻找在 Swift 3 中获取设备令牌的方法,请使用以下修改后的代码片段。

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

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

    print(deviceTokenString)

2
我不建议使用.description,因为它不能保证始终保持不变。请参见我的答案:https://dev59.com/rmox5IYBdhLWcg3wLhei#39754930 - swift taylor

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

print(token)

2
使用描述不安全,因为不能保证在将来得到相同的结果。 - Sahil Kapoor

-4

这里@kulss发表的解决方案,虽然不够优雅但却简洁明了,在iOS 13中已经不再适用,因为description在NSData中的行为发生了变化。不过你仍然可以使用debugDescription

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

-7

除非数据以null结尾,否则请尝试此方法。

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


我试过那个,它不起作用。我已经在我的代码片段中将其注释掉了。 - Sheehan Alam
@SheehanAlam 这个家伙成功了。看看它是如何转换为字符串的。https://dev59.com/NW445IYBdhLWcg3wLXWh - Naveed Ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接