我正在开发一个应用程序和一个小部件,小部件需要从app获取数据。我已经使用以下代码在NSUserDefaults上进行读写。我还使用$(PRODUCT_BUNDLE_IDENTIFIER).widget
表示小部件,$(PRODUCT_BUNDLE_IDENTIFIER)
表示this帖子。但是widget无法从app或NSUserDefaults获取数据。我怎样才能使它发挥作用?
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)")
}
答案 0 :(得分:43)
要从同一组NSUserDefaults中读取和保存,您需要执行以下操作:
写入您的NSUserDefaults:
JPM [info] Starting jpm run on erp
Creating XPI
JPM [info] XPI created at C:\Users\RAJATR~1\AppData\Local\Temp\@erp1-0.0.1.xpi (
47ms)
Created XPI at C:\Users\RAJATR~1\AppData\Local\Temp\@erp1-0.0.1.xpi
JPM [info] Creating a new profile
events.js:141
throw er; // Unhandled 'error' event
^
Error: spawn REG ENOENT
at exports._errnoException (util.js:874:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
at onErrorNT (internal/child_process.js:344:16)
at doNTCallback2 (node.js:441:9)
at process._tickCallback (node.js:355:17)
从NSUserDefaults阅读:
// In this example I´m setting FirstLaunch value to true
NSUserDefaults(suiteName: "group.myapp.test")!.setBool(true, forKey: "FirstLaunch")
// Getting the value from FirstLaunch
let firstLaunch = NSUserDefaults(suiteName: "group.myapp.test")!.boolForKey("FirstLaunch")
if !firstLaunch {
...
}
UserDefaults(suiteName: "group.myapp.test")!.set(true, forKey: "FirstLaunch")