无法使用应用程序组访问NSUserDefaults [英] Cannot access NSUserDefaults using app groups one to another
问题描述
我正在开发一个应用程序和一个小部件,小部件需要从app获取数据。我已经使用以下代码在NSUserDefaults上进行读写。我还使用 $(PRODUCT_BUNDLE_IDENTIFIER).widget
表示小部件, $(PRODUCT_BUNDLE_IDENTIFIER)
指的是这个帖子。但是widget无法从app或NSUserDefaults获取数据。我怎样才能使它工作?
I'm working on an app and a widget that the widget needs to get data from app. I've used the following codes to read and write on NSUserDefaults. And also I used $(PRODUCT_BUNDLE_IDENTIFIER).widget
for widget and $(PRODUCT_BUNDLE_IDENTIFIER)
referring to this post. But widget cannot get the data from app or NSUserDefaults. How can I make it work?
func addTask(name: String?){
let key = "keyString"
tasks.append(name!)
let defaults = NSUserDefaults(suiteName: "group.Mins")
defaults?.setObject(tasks, forKey: key)
defaults?.synchronize()
}
///////
let defaults = NSUserDefaults(suiteName: "group.Mins")
let key = "keyString"
if let testArray : AnyObject = defaults?.objectForKey(key) {
let readArray : [String] = testArray as! [String]
timeTable = readArray
timeTable = timeTable.sort(<)
print("GOT IT")
print("timetable: \(timeTable)")
}
推荐答案
阅读并保存您需要以下相同的NSUserDefaults集合:
To read and save from the same set of NSUserDefaults you need to the the following:
- 在主应用程序中,在项目导航器中选择您的项目。
- 选择主应用程序目标并选择功能选项卡。
- 启用应用程序组(这将与开发人员门户通信,因为它生成一组权利,以及相关的App Id等。)
- 创建一个新容器。根据帮助,它必须以group。开头,所以给它命名为group.myapp.test。
- 选择Today Extension目标并重复此切换过程在应用程序组。不要创建新组,而是选择这个新创建的组来表示今日延期是该组的成员。
- In your main app, select your project in the project navigator.
- Select your main app target and choose the capabilities tab.
- Switch on App Groups (this will communicate with the developer portal, as it is generating a set of entitlements, and relevant App Id and so forth).
- Create a new container. According to the help, it must start with "group.", so give it a name like "group.myapp.test".
- Select your Today Extension target and repeat this process of switching on app groups. Don’t create a new one, rather select this newly created group to signify that the Today Extension is a member of the group.
写入您的NSUserDefaults:
Write to your NSUserDefaults:
// In this example I´m setting FirstLaunch value to true
NSUserDefaults(suiteName: "group.myapp.test")!.setBool(true, forKey: "FirstLaunch")
Read来自NSUserDefaults:
Read from NSUserDefaults:
// Getting the value from FirstLaunch
let firstLaunch = NSUserDefaults(suiteName: "group.myapp.test")!.boolForKey("FirstLaunch")
if !firstLaunch {
...
}
Swift 3.0:
写
UserDefaults(suiteName: "group.myapp.test")!.set(true, forKey: "FirstLaunch")
阅读
UserDefaults(suiteName: "group.myapp.test")!.bool(forKey: "FirstLaunch")
这篇关于无法使用应用程序组访问NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!