为有牺牲多壮志,敢教日月换新天。

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

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新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")

 

posted @ 2019-04-08 14:55  为敢技术  阅读(3739)  评论(0编辑  收藏  举报