Skip to content

Instantly share code, notes, and snippets.

@stinger
Created June 17, 2016 14:58
Show Gist options
  • Save stinger/a8a0381a57b4ac530dd029458273f31a to your computer and use it in GitHub Desktop.
Save stinger/a8a0381a57b4ac530dd029458273f31a to your computer and use it in GitHub Desktop.
Swift 3: Base64 encoding and decoding strings
//: # Swift 3: Base64 encoding and decoding
import Foundation
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
var str = "Hello, playground"
print("Original string: \"\(str)\"")
if let base64Str = str.base64Encoded() {
print("Base64 encoded string: \"\(base64Str)\"")
if let trs = base64Str.base64Decoded() {
print("Base64 decoded string: \"\(trs)\"")
print("Check if base64 decoded string equals the original string: \(str == trs)")
}
}
@NicoXcc
Copy link

NicoXcc commented Mar 30, 2017

He has given all that is needed.....
[CODE]
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}

//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
[/CODE]

@yestay90
Copy link

Does somebody know how to sign files instead of string?

@enisinanaj
Copy link

I'm unable to decode this string NQABAAAAhwE= what can it be?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment