Sharing UserDefaults between main app and Widget in iOS 14

Viewed 2140

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.

2 Answers

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.

As @Ilya Muradymov commented blow

You need to set data for corresponding group UserDefault first if you want to get the data between widget and container app:

 //object-C     
 [[NSUserDefaults.alloc initWithSuiteName:@"group.com.your.groupname"] setObject:mObject forKey:@"xxxxxxxx"];
 //swift
 UserDefaults(suiteName:"group.com.your.groupname").set(mObject, forKey: "xxxxxxxx")
Related