I'm busy creating an iOS 8 Today extension for my app. I want to access my SQLite (not Core Data) database from my extension. After a little search on the web, I found out that I need an App Group. So I created an App Group for my app, named "group.AppName".
With the following code, I create a SQLite database in NSDocumentDirectory. But App Extensions can't access NSDocumentDirectory. That's why I want to save the SQLite database in my App Group.
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent: @"dbName.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:dbPathString])
{
const char *dbPath = [dbPathString UTF8String];
if(sqlite3_open(dbPath, &treinAppDB) == SQLITE_OK)
{
const char *sql_stat = "CREATE TABLE IF NOT EXISTS table (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, code TEXT, lat TEXT, lon TEXT)";
sqlite3_exec(appDB, sql_stat, NULL, NULL, &error);
sqlite3_close(appDB);
}
}
I can't figure out how I can create this database in my App Group, so I can access the database from my Today extension.
Can anybody help me with this problem? That would be great!
You have to create a database file in the containing app in the app group directory too. So the containing app and the app extension will use the same file path to a database file.
NSString *appGroupId = @"group.YourAPP.extension";
NSURL *appGroupDirectoryPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroupId];
NSURL *dataBaseURL = [directory URLByAppendingPathComponent:@"dbName.db"];
So by this way, you're creating the database file in the containing app and in the app extension you're getting the database file by the same way.