Widgets are unable to access the NSDocuments directory, which is where one would normally store their database.
The solution is to first create an App Group
Go to:
Project - Target - App Groups - Add New Container
Name the container, i.e. 'group.mycontainer'
Repeat the process for the Widget's Target using the same name for the container.
Then write your database to your group container.
So:
NSURL *storeURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSAllDomainsMask] lastObject];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];
Becomes:
NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.mycontainer"];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];
And initialising the store should be like so:
NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.mycontainer"];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];
NSPersistentStore *store = nil;
store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…