iOS 8 - Create SQLite database for App Group
Asked Answered
H

2

8

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!

Hickey answered 16/9, 2014 at 18:40 Comment(0)
S
16

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.

Schizogenesis answered 17/9, 2014 at 14:20 Comment(0)
J
0
func getTheFilePath() -> String
{
     var url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.spanglish.www") as NSURL?
     var path = url?.absoluteString?.stringByAppendingPathComponent("English.txt") as String?
     path = path!.stringByReplacingOccurrencesOfString("file:", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

     return path!
}

You can get path of container app path where you can create sqlite file and can access from both container app and extension app as well.
Please keep in mind that "Allow full Access" must be On for get path from this method

Jair answered 11/5, 2015 at 14:2 Comment(1)
But "Allow full Access" is just for keyboard extensions, right?Convene

© 2022 - 2024 — McMap. All rights reserved.