[Swift]NSString、NSData、Base64互转

前端之家收集整理的这篇文章主要介绍了[Swift]NSString、NSData、Base64互转前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

####NSString、NSData互转####

let string = "Hello world"
//NSString 转 NSData
let utf8EncodeData:NSData! = string.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true)
print("utf8EncodeData:\(utf8EncodeData)")

// var bytes: COpaquePointer { get } 只读,获取指向NSData对象内容的指针,长度为0时返回nil
//NSData 转 NSString
let bytes = utf8EncodeData.bytes
let length = utf8EncodeData.length
let stringFromData = NSString(bytes: bytes,length: length,encoding: NSUTF8StringEncoding)
print("string from data: \(stringFromData)")

####Base64互转####

let string = "Hello world"

// 将字符串进行UTF8编码成NSData
let utf8EncodeData:NSData! = string.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true)

// 将NSData进行base64编码
let base64EncodedString = utf8EncodeData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
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)")
原文链接:https://www.f2er.com/swift/325394.html

猜你在找的Swift相关文章