RileyDev
RileyDev

Reputation: 2515

How to share data with containing app using NSUserDefaults ? - Today Extension Widget

I am trying to create a Today Extension Widget which displays stored data in the widget.

Here's what I have done;

Now I have hit a road block, I am unsure the best way to retrieve and display a simple array of fetched data.

There is very little Swift tutorials and they often do not use core data.

In the main app project I fetch the array.

 let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
 let request = NSFetchRequest(entityName: "Objects")
    do {
      try
      self.objectsArray = moc.executeFetchRequest(request) as! [Objects]
    } catch {

    }

How can I use NSUserDefaults to store the objects array and then use in the today widget extension ? Or Even an array of string values.

Upvotes: 4

Views: 1398

Answers (2)

Mikita Manko
Mikita Manko

Reputation: 1113

If you set up the App Groups correct and added the same group for both Application and Extension you can use NSUserDefaults. Just for instance, to write something from the app, you need:

static func setSharedScoreNumber(score: Int) {
    let defaults = UserDefaults(suiteName: "group.bubblewrapSharedDefaults") // this is the name of the group we added in "App Groups"
    defaults?.set(String(score), forKey: "score")
    defaults?.synchronize()
}

And to read from Todays Extension:

private func getScore() -> String {
    let defaults = UserDefaults(suiteName: "group.bubblewrapSharedDefaults")
    defaults?.synchronize()
    return String(describing: defaults!.object(forKey: "score") ?? "0")
}

Here's the complete guide how to do so.

Upvotes: 0

Sasha Kozachuk
Sasha Kozachuk

Reputation: 1303

1) Get url to your database

var containerPath: String = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier‌​(YOUR_SECURITY_APP_GROUP).path 

var sqlitePath: String = "(containerPath)/("database.sqlite")"

2) Create Persistent Store Coordinator as you do in parent app.

3) Set it for your Managed Object context

context = NSManagedObjectContext()
context.persistentStoreCoordinator = coordinator

4) Retrieve objects as you do in your parent app

let moc = context
let request = NSFetchRequest(entityName: "Objects")
do {
  try self.objectsArray = moc.executeFetchRequest(request) as! [Objects]
} catch {}

Upvotes: 2

Related Questions