This is the first time I’m trying to create and access a SQLite db in iOS and I followed a tutorial, but I can’t make this work. These are the steps I’ve followed:
- Created a database through the Firefox plugin (“testDatabase”) and a
table (“testTable”) with several columns - Saved the “testDatabase.sqlite” file in a directory
- Dragged and dropped such file into my “Supporting Files” group in my
Xcode project - Added “libsqlite3.dylib” in Build Phases > Link Binary With
Libraries - Added “-lsqlite3” in Build Settings > Linking > Other Linker Flags >
Debug and Release -
In a ViewController, called this method:
-(NSString *)copyDatabaseToDocuments { NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"testDatabase.sqlite"]; if ( ![fileManager fileExistsAtPath:filePath] ) { NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"testDatabase.sqlite"]; [fileManager copyItemAtPath:bundlePath toPath:filePath error:nil]; } return filePath; } -
Then, trying to write in the database:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"testDatabase.sqlite"]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "insert into testTable (id) VALUES (?)"; sqlite3_stmt *compiledStatement; if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_int(compiledStatement, 1, newObject.ID); } if(sqlite3_step(compiledStatement) == SQLITE_DONE) { sqlite3_finalize(compiledStatement); } } sqlite3_close(database);
I have read several posts regarding a similar error, but nothing of what I tried has worked for me… I also tried with NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testDatabase" ofType:@"sqlite"]; but it is null, and also have underplayed and redeployed my app in the simulator several times…
Thanks in advance
I finally got this working by simply deleting the app folder generated in /Users/[user]/Library/Application Support/iPhone Simulator/5.1/Applications/ to be created again when running the simulator