How can I encode a string to Base64 in Swift?

前端 未结 15 783
情歌与酒
情歌与酒 2020-11-28 02:30

I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in p

15条回答
  •  星月不相逢
    2020-11-28 02:42

    You could just do a simple extension like:

    import UIKit
    
    // MARK: - Mixed string utils and helpers
    extension String {
    
    
        /**
        Encode a String to Base64
    
        :returns: 
        */
        func toBase64()->String{
    
            let data = self.dataUsingEncoding(NSUTF8StringEncoding)
    
            return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    
        }
    
    }
    

    iOS 7 and up

提交回复
热议问题