[Swift]扩展String类:Base64的编码和解码

it2022-05-06  15

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ )➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/strengthen/p/10670482.html ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

扩展方式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")

 

转载于:https://www.cnblogs.com/strengthen/p/10670482.html


最新回复(0)