iosswiftapple-watchuserdefaults

Shared UserDefaults


I want to share data between iPhone and Apple Watch with shared UserDefaults (with AppGroup), but the communication between these two doesn't work. When I look at actual stored files in the shared Container, I found out that they do not use the same container. Can someone help me with this?

Code on watch:

let suiteName = "group.suitname"
if let userDefaults = UserDefaults(suiteName: suiteName) {
   userDefaults.set(inputText, forKey: "watchTransfer")
   let groupPath = FileManager().containerURL(forSecurityApplicationGroupIdentifier: suiteName)!.appendingPathComponent("Library/Preferences")
   print(groupPath)
   print(userDefaults.string(forKey: "watchTransfer") ?? "Nothing stored")
}

Code on iPhone:

let suiteName = "group.suitname"
if let userDefaults = UserDefaults(suiteName: suiteName) {
   let string = userDefaults.string(forKey: "watchTransfer") ?? "Nothing stored"
   print("Fetched: \(string)")
   let groupPath = FileManager().containerURL(forSecurityApplicationGroupIdentifier: suiteName)!.appendingPathComponent("Library/Preferences")
   print(groupPath)
   return string
}

Solution

  • This is not possible with "modern" WatchOS.

    Reference:

    Apple developer forum

    You would need to use another transfer mechanism. Like Watchconnectivity.