How can I convert my device token (NSData) into an NSString?

后端 未结 30 1728
挽巷
挽巷 2020-11-28 18:31

I am implementing push notifications. I\'d like to save my APNS Token as a String.

- (void)application:(UIApplication *)application
didRegisterForRemoteNotif         


        
相关标签:
30条回答
  • 2020-11-28 19:12

    I think converting deviceToken to hex byte string has no sense. Why? You will send it to your backend, where it will be transformed back to bytes to be pushed to APNS. So, use NSData's method base64EncodedStringWithOptions, push it to server, and then use reverse base64decoded data :) That is so much easier :)

    NSString *tokenString = [tokenData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    0 讨论(0)
  • 2020-11-28 19:13

    Try this one unless the data is null-terminated.

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

    0 讨论(0)
  • 2020-11-28 19:14

    In iOS 13 the description will be in different format. Kindly use below code to fetch the device token.

    - (NSString *)fetchDeviceToken:(NSData *)deviceToken {
        NSUInteger len = deviceToken.length;
        if (len == 0) {
            return nil;
        }
        const unsigned char *buffer = deviceToken.bytes;
        NSMutableString *hexString  = [NSMutableString stringWithCapacity:(len * 2)];
        for (int i = 0; i < len; ++i) {
            [hexString appendFormat:@"%02x", buffer[i]];
        }
        return [hexString copy];
    }
    
    0 讨论(0)
  • 2020-11-28 19:15

    Swift 3:

    If any one is looking for a way to get device token in Swift 3. Use the below modified snippet.

        let characterSet: CharacterSet = CharacterSet( charactersIn: "<>" )
    
        let deviceTokenString: String = (deviceToken.description as NSString)
            .trimmingCharacters(in: characterSet as CharacterSet)
            .replacingOccurrences(of: " ", with: "")
            .uppercased()
    
        print(deviceTokenString)
    
    0 讨论(0)
  • 2020-11-28 19:16
    -(NSString *)deviceTokenWithData:(NSData *)data
    {
        NSString *deviceToken = [[data description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
        return deviceToken;
    }
    
    0 讨论(0)
  • 2020-11-28 19:17

    use this :

    NSString * deviceTokenString = [[[[deviceToken description]
                             stringByReplacingOccurrencesOfString: @"<" withString: @""] 
                            stringByReplacingOccurrencesOfString: @">" withString: @""] 
                           stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    NSLog(@"The generated device token string is : %@",deviceTokenString);
    
    0 讨论(0)
提交回复
热议问题