Unable to access NSUserDefaults using application groups to each other

I am working on an application and a widget that a widget needs to receive data from an application. I used the following codes to read and write to NSUserDefaults. And also I used $(PRODUCT_BUNDLE_IDENTIFIER).widget for the widget and $(PRODUCT_BUNDLE_IDENTIFIER) with a link to this post. But the widget cannot receive data from the application or NSUserDefaults. How can I make this 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)") } 
+11
ios xcode swift nsuserdefaults ios-app-group
source share
1 answer

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

  1. In the main application, select your project in the project navigator.
  2. Select the goal of your main application and go to the features tab.
  3. Turn on application groups (they will interact with the developer portal, since it generates a set of permissions, the corresponding application identifier, etc.).
  4. Create a new container. According to the help, it should start with "group.", So give it a name, for example, "group.myapp.test".
  5. Select the "Expand Today" goal and repeat this process of including application groups. Do not create a new one, instead select this newly created group to indicate 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:

Record:

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

reading:

 UserDefaults(suiteName: "group.myapp.test")!.bool(forKey: "FirstLaunch") 
+44
source share

All Articles