iosiphonewidgethomescreenios14

Sharing UserDefaults between main app and Widget in iOS 14


I am writing a widget for iOS, seems UserDefaults is not accessible in the widget, I added app group as following, still it's nil:

let prefs = UserDefaults(suiteName:"group.myco.myapp")

Still when I try to read something from prefs which I set in the main app, it's nil here.


Solution

  • You'll need to add the AppGroup capability to the widget target. Select the project, then select the widget target, go to the Signing & Capabilities tab, and click the + Capability button. Then choose AppGroup and configure it with your group.