iOS 7中的Base64解码

时间:2013-09-30 07:01:32

标签: ios objective-c swift ios7 ios8

我使用在iOS7中添加的NSString新类API编码文本(NSData)。

使用此

- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding;  

这是我的代码

NSString *base64EncodedString = [[myText dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];

NSLog(@"%@", base64EncodedString);

我想解码它

2 个答案:

答案 0 :(得分:433)

Swift 3 +

let plainString = "foo"

编码

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

解码

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift< 3

let plainString = "foo"

编码

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

解码

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

的Objective-C

NSString *plainString = @"foo";

编码

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

解码

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

答案 1 :(得分:81)

如果您想要编写回退代码,那么从一开始就通过NSURL的警告来解释来自base64的解码:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];