[英]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:我正在为 iOS 编写一个小部件,似乎在小部件中无法访问 UserDefaults,我添加了如下应用程序组,但它仍然为零:
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.仍然当我尝试从我在主应用程序中设置的prefs
中读取一些内容时,这里是零。
You'll need to add the AppGroup capability to the widget target.您需要将 AppGroup 功能添加到小部件目标。 Select the project, then select the widget target, go to the Signing & Capabilities tab, and click the + Capability
button. Select 项目,然后 select 小部件目标,go 到 Signing & Capabilities 选项卡,然后单击+ Capability
按钮。 Then choose AppGroup
and configure it with your group.然后选择AppGroup
并使用您的组进行配置。
As @Ilya Muradymov commented blow正如@Ilya Muradymov 评论打击
You need to set data for corresponding group UserDefault
first if you want to get the data between widget and container app:如果要获取widget和容器app之间的数据,需要先设置对应组UserDefault
的数据:
//object-C
[[NSUserDefaults.alloc initWithSuiteName:@"group.com.your.groupname"] setObject:mObject forKey:@"xxxxxxxx"];
//swift
UserDefaults(suiteName:"group.com.your.groupname").set(mObject, forKey: "xxxxxxxx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.