3

I'm saving my data from my main app in a file that is stored somewhere in userDomainMask.

NSKeyedArchiver.archiveRootObject(stops, toFile: BusStop.ArchiveURL.path)

and this is in my BusStop class file

static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("stops")

Now I want to read this data from my Today Extension and its returning empty set [], so I know where the issue is. I need to save this data in a shared app group that my both Extension and App belongs to.

How do I save data and read from it?

I want to save an array of instances of my BusStop class.

EDIT:

I fixed my problem!

Use this solution:

static let ArchiveURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.asd.asd.asd")!
    .appendingPathComponent("mypath")

and every time you are doing some operation on already saved data or you are saving new content use this solution:

https://stackoverflow.com/a/37162883/3595696

Cheers!

Community
  • 1
  • 1
pawisoon
  • 1,427
  • 1
  • 15
  • 20
  • did you store your file in document directory ? – KKRocks Apr 28 '17 at 11:50
  • @KKRocks yeah, its there static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! – pawisoon Apr 28 '17 at 11:50
  • why did you use archiveRootObject for this ? – KKRocks Apr 28 '17 at 11:53
  • @KKRocks This code was from apple tutorial In the saveMeals() method, add the following line of code:https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/PersistData.html#//apple_ref/doc/uid/TP40015214-CH14-SW1 – pawisoon Apr 28 '17 at 11:55

1 Answers1

6

Setup the App Group in Apple Developer Center and enable the entitlement (here is how).

Then get the the App Groups URL:

guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: applicationGroupId) else {
    fatalError("could not get shared app group directory.")
}

and use it to store common files in.

Community
  • 1
  • 1
shallowThought
  • 19,212
  • 9
  • 65
  • 112