IOS 8 - Creating an SQLite Database for an Application Group

I'm busy creating the iOS 8 Today extension for my application. I want to access my SQLite database (not the main data) from my extension. After a short search on the Internet, I found out that I needed a group of applications. So I created an application group for my application called "group.AppName".

In the following code, I create a SQLite database in NSDocumentDirectory. But application extensions cannot access NSDocumentDirectory. Therefore, I want to save the SQLite database in my application 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 understand how I can create this database in my application group, so I can access the database from my Today extension.

Can someone help me with this problem? It would be great!

+6
source share
2 answers

You also need to create a database file in the containing application in the application group directory. Thus, the containing application and the application extension will use the same path to the database file.

 NSString *appGroupId = @"group.YourAPP.extension"; NSURL *appGroupDirectoryPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroupId]; NSURL *dataBaseURL = [directory URLByAppendingPathComponent:@"dbName.db"]; 

Thus, you create a database file in the containing application and in the application extension, by which you get the database file in the same way.

+14
source
 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 the path to the container path, where you can create the sqlite file, and also access from both the container application and the extension application.
Please keep in mind that โ€œAllow full accessโ€ must be enabled in order to get the path from this method.

0
source

Source: https://habr.com/ru/post/975370/


All Articles