代码之家  ›  专栏  ›  技术社区  ›  Arsalan Haider

设备令牌为空

  •  4
  • Arsalan Haider  · 技术社区  · 10 年前

    我有一个奇怪的问题,我自己无法复制。我的一些用户正在为Apple推送通知返回空白(或空)设备令牌。这可能发生在5%的用户身上。 任何人都有过同样的问题或对此有所了解。

    我获取设备令牌的代码是:

    - (void)application: (UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData*)deviceToken
    {
        NSLog(@"My token is: %@", deviceToken);
        NSString* tokenString = [[[[deviceToken description]
                                stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                stringByReplacingOccurrencesOfString: @">" withString: @""]
                                stringByReplacingOccurrencesOfString: @" " withString: @""] ;
    
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        [def setObject:tokenString forKey:@"deviceToken"];
    
    }
    
    - (void)application: (UIApplication*)application didFailToRegisterForRemoteNotificationsWithError: (NSError*)error
    {
        NSLog(@"Failed to get token, error: %@", error) ;
    }
    
    2 回复  |  直到 10 年前
        1
  •  3
  •   trojanfoe    10 年前

    您不应该以这种方式操作设备令牌,尤其是不要使用 description 方法,它是调试辅助工具,而不是 转换为字符串 操作人员

    UIApplicationDelegate reference :

    设备令牌

    向APS标识设备的令牌。令牌是 不透明的 数据类型,因为这是提供程序需要的表单 当其向设备发送通知时,向APS服务器提交。 出于性能原因,APS服务器需要二进制格式。

    设备令牌的大小为32字节。

    注意,设备令牌与uniqueIdentifier不同 UIDevice的属性,因为出于安全和隐私原因 擦拭设备时必须更换。

    以二进制形式存储设备令牌。

        2
  •  0
  •   NoAngel    9 年前

    我是这样做的:

    - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
        NSUInteger devicetokenlen=[deviceToken length];
        char* devicetoken=(char*)malloc(devicetokenlen+1);
        memcpy(devicetoken,[deviceToken bytes],devicetokenlen);
        devicetoken[devicetokenlen]=0;
        //...
        free(devicetoken);
    

    缺陷是您不能假设令牌总是32字节长。 也许有一天会改变。所以,当通过以NULL结尾的字符数组将令牌传递到某处时,您不知道令牌的大小。例如,令牌可能包含NULL字符。因此,最好使用base64或十六进制或类似的方式转换令牌二进制数据,或者以二进制数据+大小的形式传递。