Local data lets your app work even when there is no internet. It stores information right on the device so the app can use it anytime.
0
0
Why local data enables offline functionality in iOS Swift
Introduction
When users need to see their notes without internet.
When an app shows saved photos or files offline.
When a game saves progress locally to continue later.
When an app caches data to load faster next time.
When you want to avoid delays caused by slow or no network.
Syntax
iOS Swift
UserDefaults.standard.set(value, forKey: "key") let value = UserDefaults.standard.string(forKey: "key")
UserDefaults is a simple way to save small pieces of data locally.
Use keys to store and retrieve your data easily.
Examples
Saves the name "John" locally and reads it back.
iOS Swift
UserDefaults.standard.set("John", forKey: "username") let name = UserDefaults.standard.string(forKey: "username")
Saves a boolean value to remember if user is logged in.
iOS Swift
UserDefaults.standard.set(true, forKey: "isLoggedIn") let loggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")
Sample App
This app lets you type a name, save it locally, and load it back anytime. It works without internet because data is stored on the device.
iOS Swift
import SwiftUI struct ContentView: View { @State private var username: String = "" var body: some View { VStack(spacing: 20) { TextField("Enter your name", text: $username) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() Button("Save Name") { UserDefaults.standard.set(username, forKey: "username") } Button("Load Name") { username = UserDefaults.standard.string(forKey: "username") ?? "" } Text("Saved Name: \(username)") .padding() } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
OutputSuccess
Important Notes
Local data storage is fast and works offline.
Use UserDefaults for small data; for bigger data, consider databases like Core Data.
Always handle cases when data might not exist yet.
Summary
Local data lets apps work without internet by saving info on the device.
UserDefaults is an easy way to store small pieces of data locally.
Saving and loading local data improves user experience and app speed.