TwitterCounter for @bigclick_dean

dBlog.com.au

My Development Blog

Archive for the ‘ TouchXML ’ Category

In this installment we will be creating the “framework” for our application, first up we will be creating our UITabBarController and then we will add some ViewControllers to represent our different views.

1. Create a “Window-Based” application template

I had originally intended to create the application based on a “Navigation-Based” application template but now I have decided to create everything from scratch and not use Interface Builder. So if you have already completed part 2 then I suggest you go back there and follow the instructions to create the new “Window-Based” application template.

2. Setting up the UITabBarController and its delegate

Open up RSSReaderAppDelegate.h and edit the code to look like below


#import <UIKit/UIKit.h>

@interface RSSReaderAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;

@end

What we have done here is added the UITabBarControllerDelegate and created a UITabBarController instance called tabBarController.

Now you will need to open up RSSReaderAppDelegate.m and synthesize the tabBarController instance and alter the applicationDidFinishLaunching function to look like this


- (void)applicationDidFinishLaunching:(UIApplication *)application {

tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil];

// Add the tab bar controller's current view as a subview of the window
[window addSubview:tabBarController.view];

// Override point for customization after application launch
[window makeKeyAndVisible];
}

This will allocate and init the UITabBarController and then add it to the window (we haven’t added any buttons yet, but we will do this shortly).

If you run your application now you should see the UITabBar at the bottom of the window like so:
UITabBar with no buttons

3. Creating our UINavigationController

Right Click on the Classes folder in the left hand column and click Add > New File… , the following window will appear
XCode: Add new File

Now choose UIViewController subclass and click next, now name the class MainViewController.m and click Finish.

You should now have a MainViewController.h and a MainViewController.m file in your Classes folder. Open up MainViewController.h and edit its contents to below:


#import <UIKit/UIKit.h>

@interface MainViewController : UINavigationController {
UINavigationController *navigationController;
}

@property (nonatomic, retain) UINavigationController *navigationController;

@end

Notice we have changed the subclass from UIViewController to UINavigationController and we have added a UINavigationController instance.

Now open up MainViewController.m and edit its contents to below:


#import "MainViewController.h"

@implementation MainViewController

@synthesize navigationController;

- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Main View Did Load: %@", self.tabBarItem.title);
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}

- (void)dealloc {
[super dealloc];
}

@end

All we have done here is synthesized the navigationController instance and put a NSLog call to display when the controller is created and what its TabBar item title was when it was created.

If you run the application now you wont see anything different, this is because we haven't added anything to the UITabBarController yet. To add the buttons you will need to open up the RSSReaderAppDelegate.m file and edit the applicationDidFinishLaunching function to look like below:


- (void)applicationDidFinishLaunching:(UIApplication *)application {

tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil];

// Create instances of the MainViewController for the 4 TabBar buttons
MainViewController *viewController1 = [[[MainViewController alloc] initWithNibName:nil bundle:nil] autorelease];
viewController1.tabBarItem.title = @"Browse All";
MainViewController *viewController2 = [[[MainViewController alloc] initWithNibName:nil bundle:nil] autorelease];
viewController2.tabBarItem.title = @"Most Recent";
MainViewController *viewController3 = [[[MainViewController alloc] initWithNibName:nil bundle:nil] autorelease];
viewController3.tabBarItem.title = @"Favourites";
MainViewController *viewController4 = [[[MainViewController alloc] initWithNibName:nil bundle:nil] autorelease];
viewController4.tabBarItem.title = @"Settings";
tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3, viewController4, nil];

// Add the tab bar controller's current view as a subview of the window
[window addSubview:tabBarController.view];

// Override point for customization after application launch
[window makeKeyAndVisible];
}

What we are doing here is creating 4 instances of the MainViewController and setting the tabBarItem title (this displays below TabBar icon). Once we have created all four of the View Controllers we add them to the tabBarController by setting its viewControllers property to an array containing the pointers for our 4 View Controllers. Remember that you need to have a nil value at the end of the array to indicate the last element.

If you run your application now you should see 4 TabBar items with the titles we have assigned them above. You will also notice that we have a Navigation bar at the top of our window, as we don't have a UITableView setup yet the Navigation bar will just be blank.

iPhone SDK: RSS Reader - TabBar & NavigationController working

4. Setting up our UITableViews

Now for starters we are going to need 4 UITableViewControllers for our Browse, Recent, Favourites and Settings Tabs. We will start with the stock standard ones and customize them as we go along.

Right Click the Classes folder in the left hand column and click Add > New File...
Select UITableViewController subclass and click Next
Call the first one BrowseViewController.m and then click Finish
Repeat these steps and create a RecentViewController, FavouritesViewController and SettingsViewController

Now that we have all our stock standard UITableViewControllers created we have to connect them up, we will be doing this in the MainViewController.m file, so open it up and edit its viewDidLoad function to below:


- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Main View Did Load: %@", self.tabBarItem.title);
if(self.tabBarItem.title == @"Browse All") {
BrowseViewController *browseViewController = [[BrowseViewController alloc] init];
[self pushViewController:browseViewController animated:YES];
[browseViewController release];
} else if (self.tabBarItem.title == @"Most Recent") {
RecentViewController *recentViewController = [[RecentViewController alloc] init];
[self pushViewController:recentViewController animated:YES];
[recentViewController release];
} else if (self.tabBarItem.title == @"Favourites") {
FavouritesViewController *favouritesViewController = [[FavouritesViewController alloc] init];
[self pushViewController:favouritesViewController animated:YES];
[favouritesViewController release];
} else if (self.tabBarItem.title == @"Settings") {
SettingsViewController *settingsViewController = [[SettingsViewController alloc] init];
[self pushViewController:settingsViewController animated:YES];
[settingsViewController release];
}

}

Now this may not be the most traditional method and isn't very good for massive applications that use heaps of view controllers, etc but it worked fine for my needs and meant I only needed one UINavigationController (MainViewController). What it does is it checks the title of the TabBar item that it is linked to, it then decides which UITableViewController to push into view.

Also don't forget to #import the four new header files


#import "BrowseViewController.h"
#import "RecentViewController.h"
#import "FavouritesViewController.h"
#import "SettingsViewController.h"

If you run your application now you will wee that we have a UITableView visible on each of the TabBar items, but we currently cant tell which one is which as they all look the same.

5. Identifying and Customising our UITableViews

Starting with our BrowseViewController we want to open up the BrowseViewController.m file and alter it's viewDidLoad function to below:


- (void)viewDidLoad {
[super viewDidLoad];

self.title = @"Browse All";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
}

We have set the title to "Browse All" and we have added a button to the right hand side of the navigation bar, this button is an add button (as indicated by UIBarButtonSystemItemAdd) and currently its action is set to nil, in the future we will connect this up to an UIActionSheet.

Now go through the other three controllers (RecentViewController, FavouritesViewController and SettingsController) and just set the title, not the rightBarButtonItem!

If you run your application now you should be able to navigate through it and see the title change and on the Browse All tab you should see an add button at the top right, although it wont do anything when you press it.

Browse All TabMost Recent TabFavourites TabSettings Tab

6. Download the Project Files

Click Here to download my version of the Project files, you can use these to work your way through any problems or even to work backwards to see how I do things.

7. Whats Next?

In the next installment we will be creating our SQLite database and adding some feeds and groups, we will also be setting up the BrowseViewController to handle multiple levels of groups with only one view (Drilldown) and we will also be looking at storing images in a SQLite database with a BLOB field.

PLEASE CLICK HERE TO RE-TWEET THIS TUTORIAL

Please do anything you can to spread these tutorials around as the more people that read the faster I will write tutorials!

Popularity: 15% [?]

Well I have been thinking about what features the RSS Reader tutorial should cover and I have also been getting some requests from readers (if anyone else has a request please feel free to send them through or tweet them to me).

I have come up with the following list of features and how we will be implementing them.

1. Store and retrieve RSS Feeds from a SQLite Database

We will be storing our feed details in a SQLite database and then caching the feed items in a local SQLite database once they are downloaded, this will also allow us to mark when articles have been read and also to have a favourite tab (more on this later). We will also be storing an image (favicon) in the SQLite database as a BLOB.

2. Feed Grouping and Table Drilldown

As I follow a large number of bloggers I like to be able to group my feeds into their topic or other groupings, this will also allow me to show you how to do UITableView drilldown with a single view controller. This will also go into a bit more info on SQLite and how to dynamically set a UITableViews source information.

picture-33

3. UIActionView to add RSS feed / Feed Group

This was one thing that I thought would be a nice touch, I see many people asking how to get this to work on other blogs so I thought I would include it for your enjoyment ;-)

picture-34

4. TouchXML to process RSS feeds

TouchXML is a 3rdParty library that makes manipulating and traversing XML documents a breeze, we will be using it to grab our RSS feeds and transcode them for storing in our SQLite database.

5. Integrated UIWebView

I have had many, many requests from readers for a tutorial on integrating a UIWebView with a blog reader to provide the all-in-one solution for your blog reading needs!

6. Custom Cell Renderer

Another thing that I see pop up often is requests for a tutorial on creating custom cell renderers for UITableViews, I will go through the process for creating custom cells in code.

7. UITabBarController

Originally I was just going to use a navigation controller and make the application pretty basic, but once I got all the feature requests through I realised that we would need more navigation options, I decided to use a UITabBar and Navigation Controller. This will mean a little adjustment to the “Part 2″ tutorial, but I will go back in the next installment and cover that.

8. Core Location

I have been trying to think of a way to integrate Core Location into this app, in reality there isn’t a huge need for Core Location in a RSS Reader application but I really wanted get it in there somehow…I have decided to make a server-side PHP script that will allow you to find blogs that people close to you are, don’t really know how useful it is but it will go over the basics of CoreLocation and integrating with a remote web-service.

9. What Next?

If anyone has any more feature requests them feel free to fling them my way, once this app is complete it will be submitted to the app store and hopefully approved. The full source code will be freely available for you to modify and hack up as much as you want.

In the next part we will dive into the code and start getting something running in our simulator.

Popularity: 3% [?]

This installment will walk you through creating a new Xcode project and getting everything ready to start the coding. The iPhone SDK comes ready to dive in but we need to confiure our SQLite and TouchXML libraries and get our workspace up to scratch!

1. Creating a new Xcode project

Start Xcode by clicking the icon in your dock or by running “Xcode” in your /Developer/Applications folder.

Click File > New Project and the following window will appear

Xcode New Project Window

For our RSS Reader application we are going to be using the “Window-Based Application” template, this can be found under the “iPhone OS” group in the left hand column. Simply double click the “Window-Based Application” in the Right hand column and give your project a name (I will be calling the project RSSReader).

Once you have created the project the main Xcode window will appear

Default Xcode window

2. Laying out your screen

I personally don’t like the default layout for Xcode and it can get quite hectic when you are trying to debug, code and watch the build logs at the same time. So what can you do? Thankfully Apple has provided an “All-in-one” layout and here is how you can activate it.

First you need to close your newly created project, don’t worry as it will all be saved already.
Now go to Xcode > Preferences and the following window will appear

Xcode preferences window

The General tab should be selected, if not then click on it.
You will see the “Layout” drop-down with “Default” selected, click this and choose “All-in-one” and click OK to close the window.

Now go to File > Open Recent Project and select RSSReader.xcodeproj (or whatever you called your project) from the list.

You may not notice a huge difference but there should be some icons at the top left corner of the window that will allow you to switch between the different pages (Project and Debug) and you will also now have “Project Find”, “SCM Results” and “Build” tabs in the Project page. Below is how mine looks and you will notice that I have expanded the “RSSReader” group in the left hand column.

Xcode All-in-one Window

Now that we have the All-in-one layout activated we can adjust a few things to make it a “perfect” working environment.

If you expand the “Classes” folder in the left hand column you will see a series of files (header and main files for our AppDelegate), click one of there and the right hand column should look like this.

Code Editor View

You need to drag the horizontal seperator between the two panels on the right hand side all the way to the top to give you the most code-view area possible, once you have done that it should look like this.

Resized Code Editor View

3. Add the SQLite framework to our project

By default the SQLite framework isn’t included in the project template and you will need to add it manually.

To do this you will need to right click on the Frameworks folder in the left hand pane, then click on Add > Existing Frameworks… Now navigate to /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.0.sdk/usr/lib/ and double click the “libsqlite3.0.dylib” file. This folder may change depending on the version of your iPhone SDK, the only bit that should change is the “iPhoneOS2.0.sdk” bit, this wont be a problem as it is still the same version of the framework across all the SDK releases.

The following pop-up will appear, simply click Add and the library will be added to your project.

Add Framwork Dialog

4. Add the TouchXML libraries to our project

As we will be using TouchXML for our xml parsing, we will need to import the required files we downloaded in Part 1 and also edit some of the project settings.

Go to Project > Edit Project Settings and a new window will appear with 4 tabs at the top (General, Build, Configurations and Comments). We are only interested in the Build tab at the moment, so go ahead and click the Build Tab and the following window will appear.

Project Settings Window

Make sure that you change the Configuration dropdown to “All Configurations” otherwise you may have trouble when testing on a device later on.

The settings that we are interested in are “Header Search Paths” and “Other Linker Flags”, you can easily find these by typing the beginning of the name into the Quick Find at the top right of the window.

You need to add “/usr/include/libxml2″ to the “Header Search Paths” and you need to add “-lxml2″ to the “Other Linker Flags”.

Once you have done this you can close the settings window and you will be back at your project window.

Now that the libxml2 libraries have been included you will need to import the TouchXML files to your project, to keep everything neat and tidy we will create a new “Group” to organise the files.

Right click on the “Classes” folder in the left hand column and click Add > New Group and call it TouchXML

Now its time to import the TouchXML files, simply right click on the new “TouchXML” folder in the left hand pane and click Add > Existing Files…

You will be presented with a finder window and you will need to navigate to the location that you downloaded the TouchXML files out to (in my case it was /Developer/ExtraLibraries/) and then keep going to the following path “touchcode-read-only/TouchXML/Common/Source/” and select all the files and click Add.

You should now see the CXML* files in your left hand pane and they are now available to your project.

5. And then?

We are now all setup and ready to start building the application, the next post will go over exactly what we will be building and the general structure of the application and how it will work. Remember to have a read through my other tutorial so you will have a bit of a headstart on the way to use the different technologies.

Remember to grab me on Twitter at @bigclick_dean for regular updates!

Popularity: 6% [?]

This tutorial series will walk you through the creation of a complete, ready to publish iPhone application. I have chosen to continue the Advanced RSS Reader application but I will be taking a step back and extending on some of the methods explained in those tutorials.

When this series is completed you will have learnt (hopefully!) how to setup a new iPhone application, use UITableViews & UINavigationControllers, interact with SQLite databases, read RSS/XML feeds by using TouchXML, test your project on actual iPhone hardware, prepare your application for submission to the App Store and much more.

1. Tools you are going to need

iPhone SDK -Apple has created a superb set of tools that are going to become your best friends while you work your way through this tutorial series and iPhone development in general.
TouchXML Libraries – As many of you may know the NSXMLDocument implementation was removed from the iPhone SDK due to its hefty processing requirements, so thats why we use TouchXML to provide the basic XML parsing options that we need.
SQLite Manager Plugin for FireFox – As we are going to be working with SQLite databases we need to be able to create our database structure and to browse through it easily. You can use the command line or any application that supports SQLite databases, although I have grown very fond of the SQLite Manager Plugin for Firefox (available at http://addons.mozilla.org/en-US/firefox/addon/5817)


2. Downloading & Installing the iPhone SDK

You can grab the iPhone SDK from the iPhone Dev Centre (http://developer.apple.com/iphone/), you will need to create an account to get access to the download, but don’t worry…it’s FREE!

Once the download has finished (its a heavy 1Gb+ download so now’s the best time to take a nap) you can simply run the package and go through the standard install process. By default it will install the developer tools into /Developer/ and there will no icons in your applications folder or your dock.

Under the /Developer/Applications folder you will see a bunch of applications and folder, the two we are going to be concentrating on are “Xcode” and “Interface Builder”.

picture-15picture-16

I suggest that you drag these to your dock for easy access as we are going to be using them alot! I will come back to these applications in the next tutorial as we need to install some more tools first.

3. Downloading and Setting up the TouchXML Libraries

You will need to check the latest code out from the TouchXML SVN Repository, if you don’t know how to use SVN I have included the required commands below.

1. Launch a new Terminal window
2. Create a new folder called “ExtraLibraries” where you would like to keep your iPhone development libraries (I save mine in /Developer/ExtraLibraries/ to keep evenything clean and reusable)

mkdir /Developer/ExtraLibraries

3. Change into the new folder

cd /Developer/ExtraLibraries

4. Run the SVN checkout code

svn checkout http://touchcode.googlecode.com/svn/trunk/ touchcode-read-only

You will see the filenames scrolling up the screen and depending on your connection it should only take around 60 seconds to grab all the required files. If you have a look in the newly created folder you will see the TouchXML folder along with some other libraries (TouchSQL, TouchJSON, TouchHTTPD, etc). We wont be using these other libraries but feel free to have a play around with them and see what you can do.

5. Now you have the TouchXML libraries on your local machine ready to start creating your first iPhone app.

4. Installing the SQLite Manager Plugin for FireFox

I like to use the visual editor in FireFox but by no means is it the only option, I will provide a database download for those that have trouble getting their own one built.

To install the FireFox plugin simply open up FireFox and visit http://addons.mozilla.org/en-US/firefox/addon/5817 and click “Add to FireFox”, you will need to go through the usual process of installing an add-on and after that it will be available at Tools > SQLite Manager, if you launch the manager the following window should appear:

picture-17

5. Are you ready?

Well that’s all the essential tools installed and ready to go! Go and have a play and a look at the applications and get ready for the next installment for the series.

I hear you asking “What is the next installment going to outline and when will it be out?”…The next installment is going to go through setting up a new project, organising our development windows and getting the TouchXML and SQLite libraries set up for our project. I am hoping to have the next installment out in a few hours and then it will be time to get into the “meat” of the project!

Now it’s time for a shameless plug…If you need any Web Design or Development in Australia or for that matter the world, then please check out Big Click Studios. Big Click is a Sydney Web Design Agency that I run and we do AMAZING work (I may be biased ;-) , click here to check out our portfolio.

Popularity: 8% [?]

If you are here I am guessing that you are interested in iPhone/iTouch development and are looking for a place to start. Due to Apple’s NDA on the iPhone SDK there really isn’t much information out there on getting started with iPhone development, by writing this tutorial I hope to give people the confidence to get started developing on the iPhone and also to help myself get my head around it.
Lets get started

1. Getting your development environment setup

You will need a copy of the iPhone SDK (available for free at http://developer.apple.com/iphone). Once you have downloaded the installer (it is pretty big, 1GB+) you will need to let it run and to install all the required components.

By default the installer doesn’t add any icons to anywhere so you will have to navigate to /Developer/Applications to find the tools that you will need, I suggest that you drag XCode and Interface Builder to your dock as you will be using them alot!

Fire up XCode to make sure that it launches OK, if so then you are ready to get into it!

2. Getting the TouchXML Libraries

As you cannot use the standard NSXML* libraries for iPhone development (they will work in the simulator but not when you try to deploy the app to the real hardware, I found out the hard way after working on an app for days!) we will be using the TouchXML library from TouchCode

You will need to check the latest code out from the TouchXML SVN Repository, if you dont know how to use SVN I have included the required commands below.

Launch a new Terminal window
Create a new folder called “ExtraLibraries” where you would like to keep your iPhone development libraries (I save mine in /Developer/ExtraLibraries/)

mkdir /Developer/ExtraLibraries

Change into the new folder

cd /Developer/ExtraLibraries

Run the SVN checkout code

svn checkout http://touchcode.googlecode.com/svn/trunk/ touchcode-read-only

You will see the filenames scrolling up the screen and it should only take around 30 seconds to grab all the required files.

Now you have the TouchXML libraries on your local machine ready to start creating your first iPhone app.

3. Setting up your New Project

Now its time to get into the hands on development, start up XCode if you haven’t already and click File > New Project and you will see the window below.

New Project Window

Double click on “Navigation-Based Application”, enter name your project “AdvancedBlogTutorial” and click Save.

You should see the following screen appear with all of your project files.

Initial Project Window

You can lay this screen out any way you wish but my favourite is to make the screen as large as possible and to drag the horizontal resizer all the way to the top to allow for the largest possible “code view” area as possible, like below.

My Development Layout

4. Including TouchXML in our project

As we are using TouchXML for our xml parsing, we will need to import the required files and also edit some of the project settings.

In the menu bar click Project > Edit Project Settings and a new window will appear with 4 tabs at the top (General, Build, Configurations and Comments). We are only interested in the “Build” tab at the moment, so go ahead and click the “Build” Tab and the following window will appear.

Default Project Settings Window

The settings that we are interested in are “Header Search Paths” and “Other Linker Flags”, you can easily find these by typing the beginning of the name into the “Quick Find” at the top right of the window.

You need to add “/usr/include/libxml2″ to the “Header Search Paths” and you need to add “-lxml2″ to the “Other Linker Flags”.

Once you have done this you can close the settings window and you will be back at your project window.

Now that the libxml2 libraries have been included you will need to import the TouchXML files to your project, to do this simply right click on the “Classes” folder in the left hand pane and click Add > Existing Files…

You will be presented with a finder window and you will need to navigate to the location that you checked the TouchXML files out to (in my case it was /Developer/ExtraLibraries/) and then keep going to the following path “touchcode-read-only/TouchXML/Common/Source/” and select all the files and click “Add”. You will be presented with the following screen:

Add files dialog

Leave everything as default and click “Add” .

You should now see the CXML* files in your left hand pane and they are now available for your application to use.

We are now finally setup and ready to get going.

5. Setting up our Variables, Outlets and Classes

As we used the “Navigation-Based Application” template, much of our layout and code structure has already been created for us. We could have started this from scratch but for simplicity sake it is much easy to use one of the default templates.

Open up the “RootViewController.h” file by expanding the “Classes” folder in the left hand pane and clicking once on “RootViewController.h”, you should see the contents of the right hand pane change to that of the file you selected.

By default you will see

//
//  RootViewController.h
//  AdvancedBlogTutorial
//
//  Created by dBlog on 15/09/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

}

@end

Change the code to the following

#import <UIKit/UIKit.h>
#import "TouchXML.h"

@interface RootViewController : UITableViewController {
    // This is the outlet for the blog view, it will allow the data from the controller to be used in a view
    IBOutlet UITableView *blogTable;

    // blogEntries is used to store the data retrieved from the RSS feed before being added to the view
    NSMutableArray *blogEntries;

    // loadSwirlie will display a loading overlay while the data is downloaded from the RSS feed.
    UIActivityIndicatorView *loadSwirlie;
}
@end

The first line, “#import “TouchXML.h”", will import the TouchXML library for us to use in this Controller, it is very important because if we do not include it here we will not be able to access any of the TouchXML features.

The second line, “IBOutlet UITableView *blogTable;”, will allow our view to access data from the controller, this will be where we add the individual blog entries.

The third line, “NSMutableArray *blogEntries;”, creates a new Mutable Array called blogEntries that will be where we store the RSS feed items.

Finally the forth line “UIActivityIndicatorView *loadSwirlie;”, is a view that will overlay the default “Load Swirlie” while the RSS feed is being downloaded, this is especially helpful when accessing via EDGE or when trying to read large feeds.

Save the file.

6. Digging into the core code!

Now that we have the headers all setup and our TouchXML libraries included we are ready to start on the real workhorse of the application, the RSS reader!

Open up the “RootViewController.m” file the same way that you did in the previous step.

You will see alot more code in this file as when the project was created from the template it also created most of the basic code, we will be using some of the auto-generated code and also adding some of our own.

The first thing that we want to do is to make our RSS grabbing function, to do this just paste the following code below the “@implementation RootViewController” line.

// grabRSSFeed function that takes a string (blogAddress) as a parameter and
// fills the global blogEntries with the entries
-(void) grabRSSFeed:(NSString *)blogAddress {

    // Initialize the blogEntries MutableArray that we declared in the header
    blogEntries = [[NSMutableArray alloc] init];	

    // Convert the supplied URL string into a usable URL object
    NSURL *url = [NSURL URLWithString: blogAddress];

    // Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
    // object that actually grabs and processes the RSS data
    CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];

    // Create a new Array object to be used with the looping of the results from the rssParser
    NSArray *resultNodes = NULL;

    // Set the resultNodes Array to contain an object for every instance of an  node in our RSS feed
    resultNodes = [rssParser nodesForXPath:@"//item" error:nil];

    // Loop through the resultNodes to access each items actual data
    for (CXMLElement *resultElement in resultNodes) {

        // Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
        NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];

        // Create a counter variable as type "int"
        int counter;

        // Loop through the children of the current  node
        for(counter = 0; counter < [resultElement childCount]; counter++) {

            // Add each field to the blogItem Dictionary with the node name as key and node value as the value
            [blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
        }

        // Add the blogItem to the global blogEntries Array so that the view can access it.
        [blogEntries addObject:[blogItem copy]];
    }
}

Now I know that probably looks quite confusing but I have tried to add detailed commenting to allow you to follow what It does. Basically it sends a request to the address that you specify and pulls back the response into the rssParser object. Once this is done it loops through the <item< nodes and adds it, along with its children to the global blogEntries Array.

Now that we have a function that will request, read and process a RSS feed into an Array we have to actually call it from somewhere.

Enter “viewDidAppear”!

This function will already be in your file as the template would have created it, but it will be commented out. Remove the comment tags and edit the code to look like the following:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // Check if blogEntries has already been filled, if not
    // then send the request
    if([blogEntries count] == 0) {
        // Create the feed string, in this case I have used dBlog
        NSString *blogAddress = @"http://dblog.com.au/feed/";

        // Call the grabRSSFeed function with the above
        // string as a parameter
        [self grabRSSFeed:blogAddress];

        // Call the reloadData function on the blogTable, this
        // will cause it to refresh itself with our new data
        [blogTable reloadData];
    }
}

The above code simply checks to see if the item count in blogEntries is zero, if true then it will call the grabRSSFeed function with the supplied URL and then reload the Table Outlet with the new data. You can change the URL to any valid RSS feed and it will work.

We are getting extremely close to a working application now, just a couple more small changes and we are up and running!

Ones of these is the “numberOfRowsInSection” function, if you have a look in your file you will see it up near the top and it will be returning a static value of zero. What this means is, is that every time the table is reloaded it calls this function to see how many cells it needs to draw. Currently this will always return zero and therefore it will never actually draw anything :(

What you need to do is to make it so when this function is called it returns the count of items in the blogEntries Array, this is very easy to do. Just change the “return 0;” line to the following:

return [blogEntries count];

Now whenever this function is called it will return the correct number of entries, that was easy wasn’t it?

Our final code change will actually generate the cells for the table view, we are just doing a simple cell that shows the title text, but this can be anything including icons, fonts, styles, etc.

Find the “cellForRowAtIndexPath” function in your file, then inside that function find “// Set up the cell” and enter the following code under it.

int blogEntryIndex = [indexPath indexAtPosition: [indexPath length] -1];
[cell setText:[[blogEntries objectAtIndex: blogEntryIndex] objectForKey: @"title"]];

What the above code does is it grabs the index of the item that is being generated and then calls the setText function on the cell with the “title” value of the corresponding entry in blogEntries. You could easily change this to “link”, “pubDate” or any other child node of the node.

Guess what? Its now time to run your application!

7. Running the code for the first time

Make sure that everything is saved and then click Build > Build and Go (Run), you can also press Command + Enter to do the same thing.

You should see the iPhone simulator appear and your application will start up, you should see…nothing!

What? You mean I spent all that time for an application that doesn’t even do anything?

No, no, no, It does do everything that you told it to..BUT, we forgot to link the table display to the blogTable Outlet..doh!

8. Linking the Table in the View to the blogTable Outlet

Double click on the “RootViewController.xib” file in the resources folder in the left hand pane, the “Interface Builder” application will launch with your RootViewController interface in it. You should see something similar to the image below:
Interface Builder

Now in the Main window you will see three icons, the “File’s Owner”, “First Responser” and “Table View”. What we need to do is to Control click and drag from the “File’s Owner” to the “Table View” icons, you will see a blue bar appear as you drag and when you let go over the “Table View” icon a little grey window will appear, see below:

picture-11.png

You will need to select “blogTable” as that is the Outlet we created in our header file. Once you are done you can save the interface and click “Interface Builder”.

9. The Moment of Truth

If you try to Build and Run your application now you should get some results in the screen, for my blog it looked like the following:
Mine Worked!

10. Project Files

Here are the source files for this project: Download the project source files

11. What’s Next?

Well currently you can’t really do much with the application apart from read the headers, I intend to create a series of tutorials outlining how to actually read the rest of the feeds on your phone, how to add multiple feeds and even how to add some simple animation to spruce things up. I will also be taking a look at memory management too as this tutorial hasn’t looked into this at all.

This all depends on time and also on how well this first tutorial goes. But hopefully there will be many more to come.

I hope that you all have a better idea of how to work with the iPhone SDK and also how to get the TouchXML library up and running (it took me a fair while to get my head around it!).

If you have any questions or if you find any bugs please let me know!

Until next time, bye bye!

Popularity: 45% [?]