UserDefaults API
Store small preferences like flags or last-used values.
Syntax:
UserDefaults.standard.set(_:forKey:).bool(forKey:)- SwiftUI
@AppStorage("key")
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
struct UserDefaultsDemo: View {
@AppStorage("username") private var username = ""
var body: some View {
VStack(spacing: 12) {
Text(username.isEmpty ? "Hello, Guest" : "Hello, " + username)
TextField("Username", text: $username)
.textFieldStyle(.roundedBorder)
}
.padding()
}
}
The UserDefaults API provides a simple way to store small preferences and settings, such as flags or last-used values.
Tip: For larger data or sync, use Core Data or CloudKit.
Avoid storing secrets in UserDefaults.
App Group Shared Defaults (Widget Access)
Share small values between your app and a Widget (or extensions) using an App Group suite.
Syntax:
UserDefaults(suiteName: "group.id")shared.set(_:forKey:)shared.integer(forKey:)
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
import Foundation
struct AppGroupDemo: View {
private let suite = UserDefaults(suiteName: "group.com.example.notes")!
@State private var count: Int = 0
var body: some View {
VStack(spacing: 12) {
Text("Notes count: \(count)")
HStack {
Button("Increment") { count += 1; suite.set(count, forKey: "notesCount") }
Button("Load") { count = suite.integer(forKey: "notesCount") }
Button("Clear") { suite.removeObject(forKey: "notesCount"); count = 0 }
}
}
.task { count = suite.integer(forKey: "notesCount") }
.padding()
}
}
Leave a Reply