Base64 Encode & Decode in Swift
Encode or decode below — it runs locally in your browser — then grab the canonical Swift code. Foundation's Data type provides Base64 support: encode a string to Data with .data(using: .utf8), then call .base64EncodedString(), and decode with Data(base64Encoded:).
Encode and decode a string
Encode a String by converting it to Data first, then call base64EncodedString():
import Foundation // Encode let encoded = "Hello, world!".data(using: .utf8)!.base64EncodedString() print(encoded) // SGVsbG8sIHdvcmxkIQ== // Decode let s = "SGVsbG8sIHdvcmxkIQ==" let decoded = String(data: Data(base64Encoded: s)!, encoding: .utf8) print(decoded!) // Hello, world!
Tip: Data(base64Encoded:) returns an Optional — it's nil for invalid input. Unwrap with if let or guard let rather than forcing it.
URL-safe Base64
Foundation has no built-in URL-safe encoder. Swap +// for -/_ and strip the = padding:
import Foundation
extension Data {
func base64URLEncodedString() -> String {
return base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.trimmingCharacters(in: CharacterSet(charactersIn: "="))
}
}
let url = "Hello 🌍".data(using: .utf8)!.base64URLEncodedString()
Encode an image (iOS/macOS)
On iOS, get PNG bytes from a UIImage; for any file, read it with Data(contentsOf:):
import Foundation #if canImport(UIKit) import UIKit let base64 = image.pngData()?.base64EncodedString() #endif // Any file by URL let fileData = try Data(contentsOf: fileURL) let fileBase64 = fileData.base64EncodedString()
Frequently asked questions
How do I Base64 encode a string in Swift?
Convert the string to UTF-8 Data, then encode: "Hello, world!".data(using: .utf8)!.base64EncodedString() returns "SGVsbG8sIHdvcmxkIQ==".
How do I Base64 decode in Swift?
String(data: Data(base64Encoded: s)!, encoding: .utf8) returns the text; Data(base64Encoded:) gives back the bytes.
How do I do URL-safe Base64?
Encode normally, then .replacingOccurrences(of: "+", with: "-") / ("/", "_") and trim the = padding.
Why does Data(base64Encoded:) return nil?
It's a failable initializer — it returns nil for malformed Base64 (bad length, missing padding, invalid characters). Unwrap safely instead of forcing it.
Need image, file, or URL-safe modes?
The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.
Open base64.dev →