Cannot access NSUserDefaults using app groups one to another

do it better picture do it better · Nov 20, 2015 · Viewed 11.2k times · Source

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

Answer

Rashwan L picture Rashwan L · Nov 21, 2015

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