If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.
Base64-encoding strings in Swift is very easy. You just have to convert the string to data, then encode that data with base64EncodedString() : let string = "Let's encode this string" let encoded = string. data(using: . utf8)?.
btoa() The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
Base64 Encoding Example A Base64 encoder starts by chunking the binary stream into groupings of six characters: 100110 111010 001011 101001. Each of these groupings translates into the numbers 38, 58, 11, and 41.
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()
}
}
I don’t have 6.2 installed but I don’t think 6.3 is any different in this regard:
dataUsingEncoding
returns an optional, so you need to unwrap that.
NSDataBase64EncodingOptions.fromRaw
has been replaced with NSDataBase64EncodingOptions(rawValue:)
. Slightly surprisingly, this is not a failable initializer so you don’t need to unwrap it.
But since NSData(base64EncodedString:)
is a failable initializer, you need to unwrap that.
Btw, all these changes were suggested by Xcode migrator (click the error message in the gutter and it has a “fix-it” suggestion).
Final code, rewritten to avoid force-unwraps, looks like this:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
println("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
{
// Convert back to a string
println("Decoded: \(base64Decoded)")
}
}
(if using Swift 1.2 you could use multiple if-lets instead of the map)
Swift 5 Update:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: .utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
print("Encoded: \(base64Encoded)")
if let base64Decoded = Data(base64Encoded: base64Encoded, options: Data.Base64DecodingOptions(rawValue: 0))
.map({ String(data: $0, encoding: .utf8) }) {
// Convert back to a string
print("Decoded: \(base64Decoded ?? "")")
}
}
Swift 4.2
"abcd1234".data(using: .utf8)?.base64EncodedString()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With