2 回答
TA贡献1847条经验 获得超11个赞
迅捷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
}
迅捷<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
目标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
TA贡献1859条经验 获得超6个赞
如果您想编写后备代码,则从一开始就在iOS中存在从base64进行解码的警告NSURL:
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];
return [NSData dataWithContentsOfURL:URL];
- 2 回答
- 0 关注
- 597 浏览
添加回答
举报