KellysOnTop23
KellysOnTop23

Reputation: 1435

get path for imported database in app's resource bundle swift

I have imported a Database that I made with a database browser into my swift. Now my problem is getting the path to this database. I have a FMDB wrapper in the app as well.

When I click on the resource file the Full Path description is displayed and I can use that as the path directly and I have no problem querying the database but I am not sure if that full path can be shipped with the app because it looks like it goes specifically through this computer. I tried using NSBundle.mainBundle().pathForResource("MyDatabaseName", ofType: "sqlite") but that returns nil

Basic Question: How do i get the path for my resource file/database file so that I can use it?

Thanks for any help! Super Desperate!

Upvotes: 0

Views: 2304

Answers (1)

zaph
zaph

Reputation: 112857

The problem is you are using the path in the Mac file system to the sopurce version, don't use that, you need the path in the device file system (or the simulator file system).

On the device it will look something like this:

/private/var/mobile/Containers/Bundle/Application/953D9CCB-40A2-4587-9A75-531DCE3A2DD3/AppName.app/MyDatabaseName.sqlite

On the simulator it will look something like this:

/Users/me/Library/Developer/CoreSimulator/Devices/56992263-5158-4AF5-B0CC-83E31982BB3E/data/Applications/560EEF55-2F15-4094-B20C-FF3B839AF7C2/AppName.app/MyDatabaseName.sqlite There is a path to the file in the app file system.

Here is how to find it:

  1. Open your project in Xcode
  2. In Xcode Menu : Window : Projects
  3. Select your project on the left column
  4. At the right end of Derived Data click on the arrow
  5. The Finder will open the Derived Data folder
  6. Double click your app's folder
  7. Navigate the directory tree to Build/Products/Debug-iphonesimulator
  8. You will see the file .app
  9. This is the app bundle directory.
  10. Right click (control click) and select Show Package Contents
  11. Find the DB file in this folder or a sub directory.
  12. The Bundle path is the path from this folder to the db file.

Sample code to create db path:

NSBundle *bundle = [NSBundle mainBundle];
NSString *bundlePath = [bundle bundlePath];
NSLog(@"bundlePath: %@", bundlePath);
NSString *dbPath = [bundlePath stringByAppendingPathComponent:@"<path in bundle>"];
NSLog(@"dbPath: %@", dbPath);

There are other ways to find the path (such as knowing where it is a priori) and other ways to get the path in the app but not knowing your exact configuration tis should work for you.

Upvotes: 2

Related Questions