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
SwiftyBase64 (full disclosure: I wrote it) is a native Swift Base64 encoding (no decoding library. With it, you can encode standard Base64:
let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)
or URL and Filename Safe Base64:
let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)
Swift 4.0.3
import UIKit
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
return nil
}
return String(data: data as Data, encoding: String.Encoding.utf8)
}
func toBase64() -> String? {
guard let data = self.data(using: String.Encoding.utf8) else {
return nil
}
return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
}
}
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
Swift 4.2
"abcd1234".data(using: .utf8)?.base64EncodedString()
After thorough research I found the solution
Encoding
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // bXkgcGxhbmkgdGV4dA==
Decoding
let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // my plain data
More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/
Swift
import Foundation
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}