May 30, 2008

Using the new database functionality in the iPhone

Posted in iPhone development tagged , , , , , at 4:04 am by tetontech

WebKit, and therefor Safari and the UIWebView, allows a programmer to access its’ built in SQLite database via JavaScript. Using the PhoneDataAccessObject from QuickConnectiPhone makes this very easy.

As a quick example, if you use the PhoneDataAccessObject from the QuickConnectiPhone framework, creation of a database is as simple as

//this line will create the table if it doesn't exist. If it already exists a database error is thrown that is ignored.
var database = new PhoneDataAccessObject("WelcomeExample", "1.0", "Welcome example", 20);

//this line will create the states table.
database.setData("CREATE TABLE states (id INTEGER UNIQUE, state TEXT)");

Since the QuickConnectiPhone framework supplies you with a client side session object you can just as easily store your applications current state assuming you have kept the client side session object up to date by modifying it every time the application state changed.


//serialize the client side session that stores the current state of the application
var params = [JSON.stringify(aClientSideSession)];
//insert the generated string into the states table the current state as the first record
database.setData('INSERT OR REPLACE INTO states (id, state) values( 1, ?)', params);

At startup of the application or at any time you choose you can easily retrieve the state data to reset the application’s current state to the stored state.

database.getData('SELECT state FROM states WHERE id=1');

Notice that there is no return value from the getData method. That is because all calls to the underlying SQLite database are asynchronous. The QuickConnectiPhone framework will pass the data that is the result of the query to any View Control Function you have defined where you can use the JSON library to de-serialize the stored session and use it.

See the previous post on the QuickConnectiPhone framework for more information. If you wish to see the source code for the PhoneDataAccessObject download the QuickConnectiPhone framework and open the PhoneDataAccessObject.js file. Download it here..

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: