Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)")
}
}
@vaibhav-varshaaweblabs

This comment has been minimized.

Copy link

@vaibhav-varshaaweblabs vaibhav-varshaaweblabs commented Nov 16, 2016

@stinger Can you please provide whole function to convert Base64 to Image & vice versa in Swift 3?

@NicoXcc

This comment has been minimized.

Copy link

@NicoXcc 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

This comment has been minimized.

Copy link

@yestay90 yestay90 commented Dec 12, 2017

Does somebody know how to sign files instead of string?

@enisinanaj

This comment has been minimized.

Copy link

@enisinanaj enisinanaj commented Aug 7, 2018

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