Architecting an iPhone chat app
With an installed base of 40 million iPhones, you have to be crazy if you aren't interested in writing an iOS application. But where do you start? Most applications are going to be network connected. So what about a project that spans across both, such as a chat application. In this article I show you how to build a chat application with both server and client components. You can learn much from it about creating iOS applications that I guarantee you will want to write one by the end of this article.
Building the application starts with architecting the solution. Figure 1 shows the architecture of how the iOS device (the iPhone in this case) connects to the server through two PHP pages.
Figure 1. The Chat App client/server architecture
These two PHP pages, add.php and messages.php, both connect to the database to both post and retrieve the messages, respectively. In the code that I provide, the database is MySQL, but you can use DB2 or any other database that you like.
The protocol I use is XML. The add.php page returns an XML message that says whether the message post has been successful. And the messages.php page returns the latest messages posted to the server.
Before you start, I want to cover what you will learn here.
- Database access. I show you how to use PHP to add rows to the database and retrieve them.
- XML encoding. The server code demonstrates how to package up the messages into XML.
- Building an iOS interface. I go through building the user interface for the application.
- Querying the server. The Objective-C code makes GET requests to the messages.php page to get the latest chat messages.
- Parsing the XML. Using the XML parser available to iOS developers you can parse the XML returned from messages.php.
- Displaying the messages. The application uses a custom list item to display the chat messages; this approach can give you some insight into how to customize the look and feel of your iOS application.
- Posting a message. The application POSTs data to the server through add.php, which guides you through that process.
- Timers. A timer task is used to periodically poll messages.php to see when new chat items arrive.
That's a lot for one example and it should provide a decent set of tools for you to develop any type of client/server iOS application you want to build.
Building the server
You start by creating the database. I called mine "chat," but you can call yours whatever you like. You just need to make sure that you change the connection strings in the PHP to match the name of the database. The SQL script used to build the single table for the application is in Listing 1.
Read more: IBM