Base64字符串解码时为nil的问题

2017-07-20  本文已影响69人  最晴天

对Base64字符串解码:

NSString *testStr = @"eyJleHBpcmVkIjoxNTAwNzc1OTA1NzI2LCJ1c2VySWQiOjI3fQ";
 NSInteger dValue = testStr.length%3;

//这一步的处理,只是一种尝试,尚不确定是否万能    
    for (int i = 0; i < dValue; i++) {
        testStr = [testStr stringByAppendingString:@"="];
    }

 NSData *testData = [[NSData alloc] initWithBase64EncodedString:testStr options:0];
    
   NSString *testStrDecoded = [[NSString alloc] initWithData:testData encoding:NSUTF8StringEncoding]

对字符串进行base64编码:

//测试代码
NSDictionary *dic = @{@"expired":@1500775905726,@"userId":@27};
NSData *dicData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *dicBase64Str = [dicData base64EncodedStringWithOptions:0];

 NSString *jsonStr = [[NSString alloc] initWithData:dicData encoding:NSUTF8StringEncoding];
 NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
 NSString *jsonBase64Str = [jsonData base64EncodedStringWithOptions:0];

参考:
Base64编码解码原理详解 http://blog.csdn.net/u013412497/article/details/51552335

上一篇下一篇

猜你喜欢

热点阅读