Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I specify the path for an sqlite db in an iPhone project?

After adding it as a resource, the database file itself is in the project root.

I've only been able to open it by specifying the full path as OS X sees it, i.e., "/Users/Louis/Documents/Test Project/test.db".

But of course there is no such path on an iPhone.

I think I should define the path as "application root/test.db" but I don't know how, or if that would even work anywhere else besides my development machine.

Thanks for any ideas.

like image 653
Louis Waweru Avatar asked Feb 18 '11 15:02

Louis Waweru


2 Answers

To get the path of the file you've added in XCode you would use pathForResource:ofType: with your mainBundle.

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];

But you can't change files in the mainBundle. So you have to copy it to another location. For example to the library of your app.

You could do it like this:

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"yourDB.sqlite"];

if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) {
    // database doesn't exist in your library path... copy it from the bundle
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"];
    NSError *error = nil;

    if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) {
        NSLog(@"Error: %@", error);
    }
}
like image 69
Matthias Bauch Avatar answered Sep 24 '22 15:09

Matthias Bauch


Don't just use the SQLite API, use this amazing wrapper called FMDB: https://github.com/ccgus/fmdb

like image 33
Josh Avatar answered Sep 22 '22 15:09

Josh