How to convert a base64String to String in Swift?

Try this:

let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="

var decodedString = ""
if let decodedData = Data(base64Encoded: base64Encoded) {
    decodedString = String(data: decodedData, encoding: .utf8)!
}

if !decodedString.isEmpty {
    print(decodedString)
} else {
    print("Oops, invalid input format!")
}

Make sure your base 64 encoded string is valid.

WARNING (edit)

In most base64 decoding implementations like Java, the padding-character is not needed, but Data(base64Encoded:) returns nil if it's missing.

Swift 5 solution; use String.fromBase64(_:) instead, after implementing like:

extension Data {
    /// Same as ``Data(base64Encoded:)``, but adds padding automatically
    /// (if missing, instead of returning `nil`).
    public static func fromBase64(_ encoded: String) -> Data? {
        // Prefixes padding-character(s) (if needed).
        var encoded = encoded;
        let remainder = encoded.count % 4
        if remainder > 0 {
            encoded = encoded.padding(
                toLength: encoded.count + 4 - remainder,
                withPad: "=", startingAt: 0);
        }

        // Finally, decode.
        return Data(base64Encoded: encoded);
    }
}

extension String {
    public static func fromBase64(_ encoded: String) -> String? {
        if let data = Data.fromBase64(encoded) {
            return String(data: data, encoding: .utf8)
        }
        return nil;
    }
}

As mentioned on editor's profile, above edit's code allows Apache 2.0 license as well, without attribution need.


i've made an update to Ashok Kumar S answer to add filler character when string size is not divisible by 4, raising an exception and returning nil

extension String {
func base64Encoded() -> String? {
    return data(using: .utf8)?.base64EncodedString()
}

func base64Decoded() -> String? {
    var st = self;
    if (self.count % 4 <= 2){
        st += String(repeating: "=", count: (self.count % 4))
    }
    guard let data = Data(base64Encoded: st) else { return nil }
    return String(data: data, encoding: .utf8)
}

Swift extension is handy.

extension String {
    func base64Encoded() -> String? {
        return data(using: .utf8)?.base64EncodedString()
    }

    func base64Decoded() -> String? {
        guard let data = Data(base64Encoded: self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

"heroes".base64Encoded() // It will return: aGVyb2Vz
"aGVyb2Vz".base64Decoded() // It will return: heroes

Tags:

Base64

Swift