10

I want to ship my ios application(written in swift) with my pre populated sqlite database which will be updated through syncing with server. In android I could move the db from assests folder to databases and volla, but in ios I'm quiet lost how can I achieve this?

Thanks

arash moeen
  • 4,533
  • 9
  • 40
  • 85
  • 2
    Added the prefilled database to the main bundle, on load check if the database exists in the document directory, if the file does not exists copy it from the main bundle. Then use the database in the document directory. – rckoenes Apr 16 '15 at 09:25
  • NSBundle and NSFileManager will be your friends here :) – Cocoadelica Apr 16 '15 at 09:27
  • possible duplicate of [Shipping a pre populated SQLite DB within the app. Path of the DB on startup](http://stackoverflow.com/questions/8143582/shipping-a-pre-populated-sqlite-db-within-the-app-path-of-the-db-on-startup) – 7usam Apr 16 '15 at 09:32

2 Answers2

10

In iOS you can add the database into the Project Supporting files. This will be added in with the binary, which you can then access and copy it across.

To get the location of the pre-populated database from NSBundle:

let databasePath = NSBundle.mainBundle().URLForResource("databaseName", withExtension:"sqlite3");

Get the URL of the Documents Directory using NSFileManager:

//Should have an error pointed in case there is an error.
let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain:NSSearchPathDomainMask.UserDomainMask, url:nil, shouldCreate:false, error:nil);

Finally copy the file:

if let source = databasePath, destination = documentsDirectory
{
   destination = destination.URLByAppendingPathComponent("database.sqlite3")
   var result = NSFileManager.defaultManager().copyItemAtURL(source, toURL:destination, error:nil)

   //Should have an error pointer, check that the result is true. If not check error.
}
Naughty_Ottsel
  • 1,103
  • 10
  • 12
0

The simple way is: + Choose the persistent URL is somewhere in your library folder/sub-folder (or documents if you want). + when you implement your persistentStoreCoordinator, first check if the .sqlite exists at the URL above. If not, copy your .sqlite file to that location, if yes, do nothing. + init your persistent store with that url.

You have to sure that the .sqlite's datas match the DB model

Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44