TwitterCounter for @bigclick_dean

dBlog.com.au

My Development Blog

Posts Tagged ‘ xcode ’

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% [?]

Well while I have been working on the Blog Tutorial I have been learning alot about the iPhone SDK, and once you get into it you will find that it is really quite easy to use. Even the strict data typing!

This tutorial will take you through the process of building your own web browser (well a quick one anyway, with a hard coded URL or hard coded HTML content). When I get a spare minute I will come back and show you how to use the toolbar at the top to add searching, links, etc.

1. Setup Your Project

I am not going to go into the detail of setting up XCode or anything like that in this tutorial as I did it in the RSS Reader Part 1 tutorial, if you don’t know how to set it up then I suggest heading over here and checking it out.

In the top menu click File > New Project and then under the iPhone OS area you will need to choose Window-Based Application.

Window-Based Application Template

Name your project WebBrowserTutorial and click “Save”

2. Adding the UIWebView to the window

In the left hand pane under the Resources folder double click the “MainWindow.xib” . You should see the interface builder fire up and it should look something like below, if you don’t see the inspector window (the third window in the screenshot below) then in the top menu click Tools > Inspector.

Interface Builder Default Screen

Now simply draw the “Web View” component from the library on the right to the window (the second box) and it should automatically resize itself to fit the screen.

Now that the view is on the screen you ned to make some connections, first you will need to hold the control key and click+drag from the Web View to the “File’s Owner” Object in the first screen. You should see the following popup:

iPhone WebView delegate Popup

Just click on the “delegate” Outlet and you are set!

Save and Close the Interface Builder.

3. The Code Behind the Beast (given it is a really small and simple beast)

First off we are going to setup our header file for the UIWebView Outlet.

Open up the “WebBrowserTutorialAppDelegate.h” file from under the Classes folder in the left hand pane, it should look like this

//
//  WebBrowserTutorialAppDelegate.h
//  WebBrowserTutorial
//
//  Created by Dean on 16/09/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WebBrowserTutorialAppDelegate : NSObject  {
UIWindow *window;
}

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

@end

We are going to add a UIWebView Outlet just below the “UIWindow *window” line.

The code you need to add is

IBOutlet UIWebView *webView;

What this does is it sets an UIWebView Outlet up and names it “webView” for us to use in the main controller.

Save this file and open up the “WebBrowserTutorialAppDelegate.m” file from the same classes folder.

The initial content should look something like this

//
//  WebBrowserTutorialAppDelegate.m
//  WebBrowserTutorial
//
//  Created by Dean on 16/09/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "WebBrowserTutorialAppDelegate.h"

@implementation WebBrowserTutorialAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
}

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

@end

We are going to add some code into the applicationDidFinishLaunching method that will be executed, you guessed it, after the application finishes lunching. Don’t you just love Apple’s function names?

Add the following code just below the “applicationDidFinishLaunching” line

// Example 1, loading the content from a URLNSURL
NSURL *url = [NSURL URLWithString:@"http://dblog.com.au"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

// Example 2, loading the content from a string
//NSString *HTMLData = @"<h1>Hello this is a test</h1>";
//[webView loadHTMLString:HTMLData baseURL:nil];

Most of the code above is pretty easy to understand, I have included two options for you to play with. The first one will load the content from a url (in this case it is http://dblog.com.au) and in the second example it is loading the content from a string, this string can come from anywhere, you could dynamically generate it, it could come from an XML string (like a RSS Feed ;-) ) or pretty much anywhere!

To get the second example to work you will need to comment out the first three lines and uncomment the second two.

You should be ready to save your code and fire your application up.

4. I didn’t see anything! You Suck!

Never fear, I did that on purpose. As you may notice I am trying to press the issue of linking the Outlet to the actual component as if you dont start doing that from the start you will soon get lost and your application development will drive you batty!

You will need to open up the “MainWindow.xib” file in the resources folder again and Control click+drag from the “Web Browser Tutorial App Delegate” Object (see the first image below) to the Webview component in your window. You should see the second window below appear, when it does select the “webView” Outlet.

Web Browser Tutorial App Delegate ObjectUIWebView Outlet

Save and Close the Interface Builder again and try to run your program again, if you used the first example you would see the screen below

dBlog.com.au on your own iPhone Web Browser
[ad]

5. Conclusion

Well that’s it for this tutorial, have a go at playing around with the layout and the different UIWebView loader options and let me know how you go. I will be writing some more articles on the UIWebView in the near future, and hopefully they will help some people get their head around the iPhone Development SDK.

6. Extra Features (added 27/09/2008)

After some requests I have added some extra tips below.
First one is to load a file from the application bundle.
Open up the “WebBrowserTutorialAppDelegate.m” file and edit the applicationDidFinishLaunching function to look like below:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
	NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
	[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]]; 

    [window makeKeyAndVisible];
}

What this does is it load the UIWebView content from a local file (in our case “sample.html”).

Now make a new blank file i the resources file called “sample.html” and put the following contents in it:

<html>
<head>
<title>Sample</title>
</head>
<body>
<!-- Load Image from base64 string -->
Image Loaded from base64 string:<br/>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAALwAA/
+4ADkFkb2JlAGTAAAAAAf/bAIQACQYGBgcGCQcHCQ0JBwkNDwsJCQsPEg4ODw4OEhEODw4ODw4RERQVFxUUERs
bHR0bGycmJiYnLCwsLCwsLCwsLAEKCQkKCwoMCgoMDw0ODQ8TDg4ODhMWDg4QDg4WGxQRERERFBsYGhcXFxoYH
h4bGx4eJiYkJiYsLCwsLCwsLCws/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img src="http://www.google.com.au/intl/en_au/images/logo.gif"/><br/>
This is the <strong>body</stron> of the text.<br/>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>

This is just a simple html file, but you can also embed images into the html by using their base64 value, check out http://www.abluestar.com/utilities/encode_base64/index.php for info on how to convert images into base64. By using base64 encoded strings you can build a totally self contained file with all images embedded into it.

7. Download the Project Files

I have finally added the source files for this tutorial, download it now!

Popularity: 32% [?]

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% [?]