Very simple proof of concept of using App Groups for UserDefaults. I use this in all my apps to share data between a main app and its widgets.
It consists of:
UserPreferences
: Struct that interacts with UserDefaultsPreferencesModel
: Observable wrapper forUserPreferences
, which is used in view-related codeContentView
: Very simple view to display something from preferencesMyApp
: Entry point for the app, initialises preferences and adds it to the environment
Note that it uses the Observable
protocol which requires iOS 17, but it works fine using ObservableObject
too, which is supported in all previous versions of SwiftUI.
In app extensions (like widgets) I access these the same way, either by getting it directly from UserPreferences
or PreferencesModel
.
Ensure that all targets (i.e. both your app and your widget) are members of the same app group in Signing & Capabilities > App Groups.