I have added a toggle switch to the SettingsBundle of my app to turn Cloud storage on or off:
...
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>Type</key>
<string>PSToggleSwitchSpecifier</string>
<key>Enable Cloud Storage</key>
<string>Enabled</string>
<key>Key</key>
<string>kIDCloudStorageEnabled</string>
<key>DefaultValue</key>
<true/>
</dict>
</array>
...
Then, I am using @Appstorage
to perform code (for now only a print statement) when the toggle is changed:
struct AppView: View {
@AppStorage("kIDCloudStorageEnabled") var kIDCloudStorageEnabled: Bool?
var body: some View {
// ...
}
.onChange(of: kIDCloudStorageEnabled) { [oldValue = kIDCloudStorageEnabled] newValue in
debugPrint(newValue)
}
}
}
This works, but .onChange
is not executed until my app comes back to the foreground.
How can I respond immediately when the toggle switch is flipped?