I also found that using UserDefaults.standard did not work. What helped was creating an instance of UserDefaults in both my Watch app and its complication. These two definitions use the group name from the Apps Group setting.
Each have a UserSettings.swift file (name not important) where I keep data that needs to be shared.
class UserSettings: ObservableObject {
// Define the UserDefaults instance that gets shared.
// If it can't then at least return UserDefaults.standard.
// Lets the code work when you're not focusing on complications yet.
let userDefaults: UserDefaults = {
if let defaults = UserDefaults(suiteName: "group.MyGroupName") {
return defaults
}
return UserDefaults.standard
}()
var someData: Int {
didSet {
userDefaults.set(someData, forKey: "someDatakey")
}
}
}
FYI, you can also add @Published to the individual variable definitions (e.g., someData) if your app needs to respond to changes.
(I'm also trying to figure out how to have the complication automatically update when the app changes someData.)
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: