I have a SwiftUI View with a property that is bound to @AppStorage with UserDefaults:
struct GeneralSettingsView: View {
@State var model: SettingsProtocol
var body: some View {
SettingsRowWithToggle(
title: "Toggle1",
isOn: $model.toggle1)
SettingsRowWithToggle(
title: "Toggle2",
isOn: $model.toggle2)
}
}
/// Abstract settings
protocol SettingsProtocol {
var toggle1: Bool { get set }
var toggle2: Bool { get set }
}
/// Concrete settings that are stored in userDefaults
struct UserDefaultsSettings: SettingsProtocol {
@AppStorage("toggle1", store: UserDefaults(suiteName: Constants.appGroupID))
var toggle1: Bool = false
@AppStorage("toggle2", store: UserDefaults(suiteName: Constants.appGroupID))
var toggle2: Bool = false
}
And the View is instantiated as follows in var body: ...
:
GeneralSettingsView(model: UserDefaultsSettings())
I can fetch the values from the remote server and update the value in UserDefaults:
let defaults = UserDefaults(suiteName: Constants.appGroupID)
defaults?.set(true, forKey: "toggle1") // UI not updated
defaults?.set(true, forKey: "toggle2")
I expect the toggles to change their value when i update the values in UserDefault, but it does not happen. Is it a bug or am i doing anything wrong? Is there a better way of triggering UI reload when i have UserDefault values updated in some other class?