Shared UserDefaults between app and extension not working correctly

时间秒杀一切 提交于 2019-12-04 22:50:01

I would recommend to dig down step by step here.

First, make sure that both the main app and the widget extension have app group capability enabled and use the same and activated (the checkmark must be set) app group name:

Main App:

Today Widget Extension:

Then make a simple test with direct set/get access. In your main app's AppDelegate.didFinishLaunchingWithOptions method (change the app group name and the keys to your needs):

if let userDefaults = UserDefaults(suiteName: "group.de.zisoft.GPS-Track") {
    userDefaults.set("test 1" as AnyObject, forKey: "key1")
    userDefaults.set("test 2" as AnyObject, forKey: "key2")
    userDefaults.synchronize()
}

In your Today Widget Extension's ViewController:

if let userDefaults = UserDefaults(suiteName: "group.de.zisoft.GPS-Track") {
    let value1 = userDefaults.string(forKey: "key1")
    let value2 = userDefaults.string(forKey: "key2")
    ...
}

If this works, the problem must be related in your Preferences singleton.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!