如何将设备令牌从 NSData 更改为 NSString

How to change the device token from NSData to NSString

如何将设备令牌从 NSData 更改为 NSString

  -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
        //NSString *deviceTokenString = [NSString stringWithFormat:@"%@", deviceToken];
        NSString *deviceTokenString= [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];


        NSLog(@"DeviceToken : %@", deviceToken);
        [[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:@"DeviceToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isNotificationsEnabled"];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }

下面是我的输出。

2015-01-09 11:33:22.096 SourceSage[3851:384928] DeviceToken : <cb26ce58 cc0f0229 bc1df7a2 68b4cdb5 ab6351c4 56fb4f8c 39958e8e 3f1f741a>
2015-01-09 11:33:22.109 SourceSage[3851:384928] DeviceToken : <cb26ce58 cc0f0229 bc1df7a2 68b4cdb5 ab6351c4 56fb4f8c 39958e8e 3f1f741a>

您正在将 NSData 保存到 NSUserDefaults,您需要先将 NSData 转换为 NSString,然后将其保存到 NSUserDefaults

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *token = [deviceToken description];
    token           = [token stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token           = [token stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSLog(@"DeviceToken : %@", token);
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"DeviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isNotificationsEnabled"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}