3

While both my app and extension are able to see and read/write to my shared UserDefaults object, accessed in both cases via:

if let userDefaults = UserDefaults(suiteName: "group.markl.wrshared.container") {
   ...
}

...they can only read data values that they have written themselves (Strings, in both cases). For example, if I try to read a value from the extension saved by the app:

preferredLanguage = userDefaults.string(forKey: "language")

I always get nil, but I can read userDefaults values perfectly well in the extension that were written to userDefaults in the extension. And the same is true going the other way: can't read values from the app that were written by the extension, but can read ones written by the app.

To me it seems obvious that I must be actually writing to different UserDefaults objects, but I have done many iterations of changing the group name, the App Groups listing in each target's Signing and Capabilities section, making sure to use UserDefaults.synchronize() etc. If they really are writing to different UserDefaults objects I'm at a loss to explain.

I'd be very grateful for any solutions or ideas for how to troubleshoot the problem!

Mark
  • 51
  • 2
  • 1
    App Group must be the same for the app and the extension, and you must use the group name as `suiteName` as well. – storoj Jul 07 '20 at 11:32
  • Argh, I'm stupid. Also, I wish I'd asked sooner--many hours have been lost :) – Mark Jul 07 '20 at 11:55
  • To me it wasn't obvious that the App Group is the same as the suiteName; my App Group was named group.markl.wrshared and I added a .container for my suiteName. So this means that an App Group may only contain one UserDefaults object? – Mark Jul 07 '20 at 11:57
  • @storoj, please add this as an answer, as I spent 1 day to find this. – Display Name Feb 20 '23 at 17:23
  • @DisplayName done, no idea why did I comment back then – storoj Feb 21 '23 at 18:55

1 Answers1

1

To get the desired behaviour the App Group must be the same for both the app and the extension, and you must use that name as suiteName.

storoj
  • 1,851
  • 2
  • 18
  • 25