美文网首页iOS优秀开发文章
关于iOS 13 获取Token

关于iOS 13 获取Token

作者: 红凉梦 | 来源:发表于2019-12-25 09:56 被阅读0次
    //获取DeviceToken成功
    - (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
        //Xcode11打的包,iOS13获取Token有变化
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 13) {
            if (![deviceToken isKindOfClass:[NSData class]]) {
                //记录获取token失败的描述
                return;
            }
            const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
            NSString *strToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                  ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                  ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                  ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
            NSLog(@"deviceToken1:%@", strToken);
            return;
        } else {
            NSString *token = [NSString
                           stringWithFormat:@"%@",deviceToken];
            token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
            token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
            token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSLog(@"deviceToken2 is: %@", token);
        }
    }
    

    xcode 11下,你打印deviceToken 是这样的格式
    <xxxxxx xxxxxx xxxxxx ..... x xxxxxx>,而实际我们需要获取的是这样的:xxxxxxxxxxxxxxxxxxxxx

    处理

    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    [self formatToken: token];
    //去掉两边尖括号和中间空格
    -(NSString *)formatToken:(NSString *)token {
        
        NSString *t = [[token substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)];
        t = [t stringByReplacingOccurrencesOfString:@" " withString:@""];
        return t;
    }
    

    相关文章

      网友评论

        本文标题:关于iOS 13 获取Token

        本文链接:https://www.haomeiwen.com/subject/gsnqoctx.html