在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 扩展方式1: 1 extension String { 2 //Base64编码 3 func encodBase64() -> String? { 4 if let data = self.data(using: .utf8) { 5 return data.base64EncodedString() 6 } 7 return nil 8 } 9 10 //Base64解码 11 func decodeBase64() -> String? { 12 if let data = Data(base64Encoded: self) { 13 return String(data: data, encoding: .utf8) 14 } 15 return nil 16 } 17 } 扩展方式2: 1 extension String { 2 //Base64编码 3 func encodBase64() -> String? 4 { 5 let strData = self.data(using: String.Encoding.utf8) 6 let base64String = strData?.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0)) 7 return base64String 8 } 9 10 //Base64解码 11 func decodeBase64() -> String? 12 { 13 let decodedData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions.init(rawValue: 0)) 14 let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue) as String? 15 return decodedString 16 } 17 } 测试代码: 1 var str:String = "Strengthen" 2 let strBase64:String = str.encodBase64()! 3 print(strBase64) 4 //Print U3RyZW5ndGhlbg== 5 6 print(strBase64.decodeBase64()) 7 //Print Optional("Strengthen")
|
请发表评论