- 图片 和 String 之间
图片转 String
let image = UIImage();
let imgData = UIImagePNGRepresentation(image);
print(imgData?.base64EncodedString())
String 转 图片
let imageStr:String = "iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAg...中间省略若干字符gg==";
if var data: NSData = NSData(base64Encoded: imageStr, options:NSData.Base64DecodingOptions.ignoreUnknownCharacters)
{
if var image: UIImage = UIImage(data: data as Data)
{
let imageView = UIImageView(image: image)
self.view.addSubview(imageView)
}
}
- NSData 和 String 之间
do {
//data to string
let data: Data = try Data(contentsOf: url! as URL)
let str = String(data: data, encoding: String.Encoding.utf8)
//string to data
let data:Data = str.data(using: String.Encoding.utf8))!
catch {
print("Error: (data: contentsOf: url)")
}
Base64互转
let string = "Hello world"
// 将字符串进行UTF8编码成NSData
let utf8EncodeData:NSData! = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// 将NSData进行base64编码
let base64EncodedString = utf8EncodeData?.base64EncodedString()
print("encodedString: \(base64EncodedString)")
// 将base64字符串转换成NSData
let base64EncodedData = NSData(base64EncodedString:base64EncodedString,options:NSDataBase64DecodingOptions(rawValue: 0))
// 对NSData数据进行UTF8解码
let stringWithDecode = NSString(data: base64EncodedData!, encoding: NSUTF8StringEncoding)
print("base64String: \(stringWithDecode)")