Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS ship application with pre populated sqlite database [closed]

Tags:

sqlite

ios

swift

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

like image 469
arash moeen Avatar asked Apr 16 '15 09:04

arash moeen


1 Answers

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.
}
like image 68
Naughty_Ottsel Avatar answered Oct 17 '22 18:10

Naughty_Ottsel