Coder
Coder

Reputation: 1681

Accessing database file in xcode

I have an existing database file. I want to use this db file in a project. I placed this file in my app folder in mac and dragged the same into Xcode. And now I have written the code to check whether the file exists or not. But it is throwing FALSE exception.

 bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:@"school.db"];

Please let me know how to use the existing db files.

Thanks

Upvotes: 0

Views: 1928

Answers (4)

Ilker Baltaci
Ilker Baltaci

Reputation: 11779

Try getting the path with

NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"school" ofType:@"db"];

For Swift:

let dbPath = Bundle.main.path(forResource: "school", ofType: "db")

Upvotes: 2

Mike M
Mike M

Reputation: 4436

It depends on whether or not you need the database to be writable.

You can get access to the database just by doing this:

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];

but if you've copied it to another directory so you can write to it (e.g. the Documents directory), you'd need to do something like this to get the path:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"];

Upvotes: 0

Nenad M
Nenad M

Reputation: 3055

I suppose you're using Core Data in your project, aren't you? If so take a look at the iPhone Core Data Recipes sample project by Apple! In the Classes/​RecipesAppDelegate.m you'll find sample code for accomplishing what you need!

There's a good tutorial about pre-loading over at Ray Wenderlich's site. Shipping a pre-loaded database in the way the Core Data Recipes example showcases is not the most desireable way by Apple. So please take a look at the provided tutorial for a more sophisticated approach!

Upvotes: 0

sosborn
sosborn

Reputation: 14694

Without knowing what type of DB it is (MySQL, SQLITE, etc.) the best I can tell you is to find an iOS appropriate library/wrapper to access the database. As an example. FMBD if very good for SQLITE.

Upvotes: 0

Related Questions