I’m working on bringing some of my works over to the iPhone and iPad and in doing so I decided to use MonoTouch (since I have a strong .NET background and absolutely no Objective-C experience other than some evaluation work). The long term plan is to master MonoTouch, which will familiarize me with Cocoa, iPhone/iPad idiocies, and Interface Builder. After that, I’ll hop over and learn Objective-C and move all dev over there. Right now though, its all about getting an app done.
I have a SQLite DB that contains a few thousand records that need to be seeded before users can use my app. I have two options at this point:
Option 1 is probably what most people will do.
Option 2 is what not many people do in MonoTouch (I’m assuming), but would like to.
I have opted for option #2. Unfortunately there is no documentation saying HOW to do this in MonoTouch (that I can find). In the end, it’s a fairly simple process. Here’s how I went about it.
Figure 1: Add the db file to the project. The “workouts.db3″ is my DB file.
Figure 2: Set the Build action to “Content”
Listing 1: Code that will copy the “workouts.db3″ from the application package into the iOS folder so you can use it.
public void CopyDb ()
{
string dbname = "workouts.db3";
string documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // This goes to the documents directory for your app
string db = Path.Combine(documents, dbname);
string rootPath = Environment.CurrentDirectory; // This is the package such as MyApp.app/
string rootDbPath = Path.Combine(rootPath, dbname);
Console.WriteLine("Root Db Path: " + rootDbPath);
Console.WriteLine("Final Db Path: " +db);
if(File.Exists(db) == false) {
Console.WriteLine("Copying DB!");
File.Copy(rootDbPath, db);
} else {
Console.WriteLine("DB Exists, not copying.");
}
}
When FinishedLaunching is called, I call “CopyDb” and this method takes care of the rest. What it does is check for existence of the db and if it exists it will NOT copy it. If it does not, it will copy it. The only time this should be run is the first time the user installs the app.
If you’re having a hard time understanding the iOS file structure, I highly recommend reading Rory Blyths explanation on this SO post. He covers the basics of the iOS sandbox very well. Thanks for the post Rory.
You should now be set to connect to the db using the SQLite code you’ve see in other MonoTouch examples.