【问题标题】:What encoding is the device token for APNs in?APN 的设备令牌采用什么编码?
【发布时间】:2011-04-10 23:05:17
【问题描述】:

是否可以获取应用程序返回的Device Token:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 方法?由于我不太擅长 PHP,我希望我的用户手动将令牌输入到他们计算机上的程序中,该程序将用于发送通知。但是,我无法从这种方法中获取令牌。它使用 NSLog 记录良好,但是当我使用 NSString initWithData: 时,我总是得到一些神秘的东西。我想编码是错误的?

提前感谢您的帮助!

【问题讨论】:

    标签: notifications push device token apple-push-notifications


    【解决方案1】:

    令牌是一个 NSData 对象,它指向原始二进制数据块,而不是字符串。将其转换为字符串的两种最常见的方法是:

    1. base64 编码 下载http://projectswithlove.com/projects/NSData_Base64.zip
    NSString *str = [deviceToken base64EncodedStringWithoutNewlines];
    
    1. 使用 NSData 的 -description 获取字符串十六进制转储并清理它
    NSString *str = [[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@">" withString:@""];
    str = [str stringByReplacingOccurrencesOfString: @" " withString: @""];
    

    我更喜欢 #1,因为后者取决于 NSData 的 -description 调用工作的内部方式,但两者都应该工作。

    【讨论】:

    • 我使用 base64 方法,但使用 'url safe' base64 这是一种编码,使生成的字符串可以接受,因为 - 在 URL 等中。原始 base64 使用 '+' 和 '/ '标准Base64的字符分别替换为'-'和'_'。
    【解决方案2】:

    不用担心NSDatadescription方法的行为,你可以得到十六进制字符串,有:

    + (NSString *)hexadecimalStringFromData:(NSData *)data {
        NSMutableString *hexToken;
        const unsigned char *iterator = (const unsigned char *) [data bytes];
        if (iterator) {
            hexToken = [[NSMutableString alloc] init];
            for (NSInteger i = 0; i < data.length; i++) {
                [hexToken appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) iterator[i]]];
            }
            return hexToken;
        }
        return nil;
    }
    

    【讨论】:

      【解决方案3】:

      token是NSData,可以转成字符串,去掉和空格

      NSString *devToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
      devToken = [devToken stringByReplacingOccurrencesOfString:@" " withString:@""];
      
      
      NSLog(@"token: %@",devToken);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 1970-01-01
        相关资源
        最近更新 更多