Created
June 17, 2016 14:58
-
-
Save stinger/a8a0381a57b4ac530dd029458273f31a to your computer and use it in GitHub Desktop.
Swift 3: Base64 encoding and decoding strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: # 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)") | |
} | |
} |
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
Does somebody know how to sign files instead of string?