0

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

4 Answers 4

2

Try getting the path with

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

For Swift:

let dbPath = Bundle.main.path(forResource: "school", ofType: "db")
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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!

1 Comment

Pretty sure he isn't using Core Data if it is an existing DB.
0

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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.