Cannot access NSUserDefaults using app groups one to another

自闭症网瘾萝莉.ら 提交于 2019-12-18 04:03:10

问题


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)")
}

回答1:


To read and save from the same set of NSUserDefaults you need to the the following:

  1. In your main app, select your project in the project navigator.
  2. Select your main app target and choose the capabilities tab.
  3. 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).
  4. Create a new container. According to the help, it must start with “group.”, so give it a name like “group.myapp.test”.
  5. 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.

Write to your NSUserDefaults:

// In this example I´m setting FirstLaunch value to true 
NSUserDefaults(suiteName: "group.myapp.test")!.setBool(true, forKey: "FirstLaunch")

Read from NSUserDefaults:

// Getting the value from FirstLaunch
let firstLaunch = NSUserDefaults(suiteName: "group.myapp.test")!.boolForKey("FirstLaunch")

if !firstLaunch  {
   ...
}

Swift 4.x:

Write:

UserDefaults(suiteName: "group.myapp.test")!.set(true, forKey: "FirstLaunch")

Read:

UserDefaults(suiteName: "group.myapp.test")!.bool(forKey: "FirstLaunch")


来源:https://stackoverflow.com/questions/33834002/cannot-access-nsuserdefaults-using-app-groups-one-to-another

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