iOS development
base64 encoding
Swift programming
iOS tutorial
mobile app development

How do I do base64 encoding on iOS?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Base64 encoding on iOS is built into Foundation, so you usually do not need any extra library. The core pattern is simple: turn your text or bytes into Data, call base64EncodedString(), and reverse the process when you need to decode.

The important details are knowing whether the data is text or binary, handling invalid input safely, and remembering that Base64 is only an encoding scheme. It is not encryption and it provides no secrecy by itself.

Encode Text to Base64

For strings, convert the text into Data first and then ask Foundation for the Base64 representation:

swift
1import Foundation
2
3let input = "Hello iOS"
4let data = Data(input.utf8)
5let encoded = data.base64EncodedString()
6
7print(encoded)

This is the standard pattern for tokens, debug output, or API payloads that need to carry text through a text-only channel.

Decode Base64 Back to Text

Decoding is the reverse: create Data from the Base64 string, then build a String from the decoded bytes if the payload is actually text.

swift
1import Foundation
2
3let encoded = "SGVsbG8gaU9T"
4
5if let decodedData = Data(base64Encoded: encoded),
6   let text = String(data: decodedData, encoding: .utf8) {
7    print(text)
8} else {
9    print("invalid Base64 input")
10}

The optional checks matter. Malformed Base64 or a mismatched text encoding should be treated as normal error cases, not as impossible states.

Work With Binary Data Too

Base64 is often used for binary data such as images, files, and cryptographic material. In that case, the decoded result may not be meaningful as text, so keep it as Data.

Encoding raw bytes:

swift
1import Foundation
2
3let bytes = Data([0x48, 0x69, 0x21])
4let encoded = bytes.base64EncodedString()
5
6print(encoded)

Decoding back to bytes:

swift
1import Foundation
2
3let encoded = "SGkh"
4
5if let decoded = Data(base64Encoded: encoded) {
6    print(decoded as NSData)
7}

That is the right approach for file reconstruction, image uploads, or binary protocol handling.

Create Small Reusable Helpers

If the same conversion appears in several parts of the app, hide the mechanics behind small helpers:

swift
1import Foundation
2
3enum Base64Util {
4    static func encodeText(_ text: String) -> String {
5        Data(text.utf8).base64EncodedString()
6    }
7
8    static func decodeText(_ encoded: String) -> String? {
9        guard let data = Data(base64Encoded: encoded) else {
10            return nil
11        }
12        return String(data: data, encoding: .utf8)
13    }
14}
15
16print(Base64Util.encodeText("token:123"))
17print(Base64Util.decodeText("dG9rZW46MTIz") ?? "decode failed")

This keeps view controllers and networking code focused on business logic rather than repeated byte-conversion details.

Handle URL-Safe Base64 When APIs Require It

Some web APIs use a URL-safe Base64 variant where plus becomes hyphen, slash becomes underscore, and padding may be removed. Foundation handles standard Base64 directly, so URL-safe input often needs normalization first.

swift
1import Foundation
2
3func toBase64URL(_ data: Data) -> String {
4    data.base64EncodedString()
5        .replacingOccurrences(of: "+", with: "-")
6        .replacingOccurrences(of: "/", with: "_")
7        .replacingOccurrences(of: "=", with: "")
8}
9
10print(toBase64URL(Data("abc123".utf8)))

If you need to decode that format, reverse those substitutions and restore the padding before calling Data(base64Encoded:).

Common Pitfalls

The most common mistake is treating Base64 as a security feature. It is not. Anyone who receives the string can decode it easily.

Another common problem is assuming the decoded bytes always represent UTF-8 text. Sometimes the correct result is binary data and should remain as Data.

Developers also force-unwrap Base64 decoding and crash on malformed input. Invalid data should be handled as a normal failure path.

Finally, when integrating with web APIs, confirm whether the other side expects standard Base64 or a URL-safe variant. The strings look similar, but the details matter.

Summary

  • Base64 support on iOS is built into Foundation Data.
  • Encode by converting text or bytes to Data and calling base64EncodedString().
  • Decode safely with Data(base64Encoded:) and optional handling.
  • Keep binary payloads as Data instead of forcing them into strings.
  • Treat Base64 as encoding, not encryption, and watch for URL-safe variants.

Course illustration
Course illustration

All Rights Reserved.