TechBuzzPro

How to Save Local Data in a Swift App

· 4 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To save local data in a Swift app, use Apple's built-in persistence frameworks: UserDefaults for small preferences, the file system for larger files, and Core Data or SwiftData for structured objects. All three work offline and require no third-party library. The right choice depends on what you are storing and how much of it there is.

What You'll Need

  • Xcode installed on a Mac, with a SwiftUI or UIKit project open.
  • A basic understanding of Swift types such as String, Int, and Codable structs.
  • An iOS, iPadOS, or macOS target (the same APIs work on all Apple platforms, though menu labels and file locations can differ slightly by version and device).

Step-by-Step

  1. Decide what kind of data you are saving. Use UserDefaults for small values like a username, a toggle state, or a high score. Use files for images, JSON exports, or anything larger than a few kilobytes. Use Core Data or SwiftData when you need to query, sort, or relate many records. Mixing these up is the most common cause of slow apps and lost data.
  2. Save a simple value with UserDefaults. Call UserDefaults.standard.set(value, forKey: "myKey") where value is a String, Int, Bool, Double, or Data. Read it back with UserDefaults.standard.string(forKey: "myKey") or the matching typed getter. UserDefaults writes to disk automatically, so you do not need a save call.
  3. Store a custom struct as Codable data. Make your struct conform to Codable, encode it with JSONEncoder().encode(myStruct), and save the resulting Data in UserDefaults. Decode it with JSONDecoder().decode(MyStruct.self, from: data). This keeps small objects tidy without a database.
  4. Write larger data to a file. Get a directory with FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!, append a filename, and write with try data.write(to: url, options: .atomic). The .atomic option prevents a half-written file if the app crashes mid-save. Read it back with try Data(contentsOf: url).
  5. Use SwiftData for structured records. In a SwiftUI app, add a model with the @Model macro, attach a ModelContainer to your view hierarchy, and insert objects through the model context. SwiftData handles saving, fetching, and relationships. Core Data remains the older alternative and uses the same underlying store; pick one and stay consistent.
  6. Handle errors instead of ignoring them. Wrap file writes and decodes in do/catch and log the error. A silent failure here is why data appears to vanish between launches.
  7. Test persistence across launches. Run the app, save a value, stop it in Xcode, and run again. If the value is missing, check that you are reading the same key or file path and that the write actually executed.

Common Mistakes

  • Using UserDefaults for large data. It loads into memory at launch; storing images or long lists there slows startup and is not what it is designed for.
  • Forgetting the atomic write option. A crash during a plain write can leave a corrupt file that fails to decode on the next launch.
  • Hardcoding file paths. The app's container path changes between installs and devices. Always build paths from FileManager URLs.
  • Ignoring thread safety. Core Data and SwiftData contexts are not safe to share across threads without the proper context setup. Keep UI work on the main context.
  • Assuming data survives app deletion. Removing the app deletes its container, including files and databases. UserDefaults is also cleared. Only iCloud or an external backup preserves it.

Tips

  • Keep keys in one constants file so a typo in a string does not silently create a second, empty entry.
  • Version your saved JSON with a schema field so future changes can migrate old data instead of crashing on decode.
  • Use FileManager's application support directory for app-managed data and the documents directory only for files the user should see.
  • For sensitive values like tokens, use the Keychain instead of UserDefaults; UserDefaults is not encrypted.
  • Write a small unit test that saves, reloads, and compares the value. It catches most persistence regressions early.

Troubleshooting

If saved data is missing after relaunch, first confirm the write ran by adding a print or breakpoint right after the save call. Then check that the read uses the identical key or filename. If you changed the struct's properties, old JSON may no longer decode; add default values or a migration step. If file writes fail, verify you are writing inside the app's container and not to a read-only location. If Core Data or SwiftData fetches return nothing, confirm the model container was attached before the view that queries it. As a last resort, delete the app from the simulator or device and reinstall to clear a corrupted store, but note this erases all locally saved data.

Frequently Asked Questions

Is UserDefaults safe for passwords?

No. It is stored unencrypted. Use the Keychain for passwords and tokens.

Does local data sync between devices?

Not by default. Local storage stays on one device unless you add iCloud or another sync layer.

Can I use these APIs on macOS and watchOS?

Yes. UserDefaults, FileManager, Core Data, and SwiftData are available across Apple platforms, with some API differences on watchOS.

What happens to saved data when the app is updated?

It is preserved. Updating an app keeps its container; only deleting the app removes local data.

Should I use Core Data or SwiftData?

SwiftData is the newer, simpler option for new SwiftUI projects. Core Data is still valid for existing apps and older deployment targets.