Saturday, July 11, 2009

Deploying iphone application with SQLite database for ad hoc distribution

So...its nice to write something after a while. I have been working on iphone applications lately. I had come across issues and figured the solutions too, but I am still little unsure of what information can be made public and what cannot. (Apple's copy right thing.)

For Ad hoc distribution, I installed my app on my iphone for testing, app was installed fine but the data was blank. The problem was that the database wasn't copied over. After a little fight, found the solution below.

You need to add the sqlite file to you XCode project, in the resources folder. Then in your app delegate code file, in the appDidFinishLaunching method, you need to first check if a writable copy of the sqlite file has already been created - ie: a copy of the sqlite file has been created in the users document folder on the iphone's file system, if yes, you don't do anything, else you would overwrite it with the default xcode sqlite copy.

See below code example to do this. This method is called from the app delegates appDidFinishLaunching method.


// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bookdb.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}