Using NSXMLParser to Pull UIImages From the Web
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
Introduction
Hello everyone, welcome to my third screeencast. This screencast is the result of a request made in the comments of my first post. I am going to be covering many topics in this post. But the general idea of the app we will build is that it will use an XML file online to get the URL and title of a given picture. For each URL and Title pair a view will be created with a UIImageView showing the image and a UILabel showing the title. Each of these views will be placed in a UIScrollView to flip through, like th functinoality of the Photos app.
Skill Level Medium
This app is going to require a decent amount of experience with Objective C and xCode. Also some minimal understanding of XML and XML schema/structure would be valuable.
Source Code
Available Here
Screencast
I film myself coding out the entire sample project for each post. I personally think going through the Screencast is the best way to learn. But feel free to look through the slides and text if that suites you better.
Using NSXML to Pull UIImages From the Web Screencast
SCREENCAST ADDITION
Adding a final line to layoutSubviews should be:
[scrollview setFrame:workingFrame]; this will stop the scroll view from bouncing up and down.
Tutorial













iCodeBlogXMLImagesViewController.h:
@interface iCodeBlogXMLImagesViewController : UIViewController
{
IBOutlet UIScrollView *scrollview;
}
@property (nonatomic, retain) IBOutlet UIScrollView *scrollview;
iCodeBlogXMLImagesViewController.m
@synthesize scrollview;




iCodeBlogXMLView.h:
@interface iCodeBlogXMLView : UIView
{
IBOutlet UIImageView *imageView;
IBOutlet UILabel *title;
}
@property (nonatomic, retain) IBOutlet UIImageView *imageView;
@property (nonatomic, retain) IBOutlet UILabel *title;
@end
iCodeBlogXMLView.m
@synthesize imageView; @synthesize title;




iCodeBlogXMLElement.h:
@interface iCodeBlogXMLElement : NSObject
{
UIImage *image;
NSString *imageTitle;
}
@property (nonatomic, retain) UIImage *image;
@property (nonatomic, retain) NSString *imageTitle;
@end
iCodeBlogXMLElement.m
@synthesize image; @synthesize imageTitle;




iCodeBlogXMLImagesViewController.h:
#import <UIKit/UIKit.h>
#import "iCodeBlogXMLElement.h"
#import "iCodeBlogXMLView.h"
@interface iCodeBlogXMLImagesViewController : UIViewController
{
IBOutlet UIScrollView *scrollview;
NSXMLParser *parser;
NSMutableString *currentAttribute;
NSMutableArray *xmlElementObjects;
iCodeBlogXMLElement *tempElement;
}
@property (nonatomic, retain) IBOutlet UIScrollView *scrollview;
@property (nonatomic, retain) NSXMLParser *parser;
@property (nonatomic, retain) NSMutableString *currentAttribute;
@property (nonatomic, retain) NSMutableArray *xmlElementObjects;
@property (nonatomic, retain) iCodeBlogXMLElement *tempElement;
-(void)layoutSubview;
@end
iCodeBlogXMLImagesViewController.m
@implementation iCodeBlogXMLImagesViewController
@synthesize scrollview;
@synthesize parser;
@synthesize currentAttribute;
@synthesize xmlElementObjects;
@synthesize tempElement;
...
- (void)viewDidLoad
{
[super viewDidLoad];
xmlElementObjects = [[NSMutableArray alloc] init];
parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://losectrl-gaincommand.com/iCodeBlogHelper/Tutorial3/iCodeBlogImageXML.xml"]];
[parser setDelegate:self];
[parser parse];
}
...
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
}




iCodeBlogXMLImagesViewController.m
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if(![elementName compare:@"PictureInfo"])
{
tempElement = [[iCodeBlogXMLElement alloc] init];
}
else if(![elementName compare:@"imageURL"])
{
currentAttribute = [NSMutableString string];
}
else if(![elementName compare:@"imageTitle"])
{
currentAttribute = [NSMutableString string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if(![elementName compare:@"PictureInfo"])
{
[xmlElementObjects addObject:tempElement];
}
else if(![elementName compare:@"imageURL"])
{
NSURL *imageURL = [NSURL URLWithString:currentAttribute];
NSData *data = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [[UIImage alloc] initWithData:data];
[tempElement setImage:image];
}
else if(![elementName compare:@"imageTitle"])
{
NSLog(@"The image title is %@", currentAttribute);
[tempElement setImageTitle:currentAttribute];
}
else if(![elementName compare:@"Pictures"])
{
[self layoutSubview];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(self.currentAttribute)
{
[self.currentAttribute appendString:string];
}
}

iCodeBlogXMLImagesViewController.m
-(void)layoutSubview
{
CGRect workingFrame;
workingFrame.origin.x = 0;
workingFrame.origin.y = 0;
workingFrame.size.height = 480;
workingFrame.size.width = 320;
iCodeBlogXMLView *myView;
for(iCodeBlogXMLElement *element in [self xmlElementObjects])
{
myView = [[iCodeBlogXMLView alloc] initWithFrame:workingFrame];
NSLog(@"Element title is: %@", [element imageTitle]);
NSArray *topLeveObjects = [[NSBundle mainBundle] loadNibNamed:@"iCodeBlogXMLView" owner:nil options:nil];
for(id currentObject in topLeveObjects)
{
if([currentObject isKindOfClass:[iCodeBlogXMLView class]])
{
myView = (iCodeBlogXMLView *)currentObject;
}
}
[[myView imageView] setImage:[element image]];
[[myView title] setText:[element imageTitle]];
[myView setFrame:workingFrame];
[scrollview addSubview:myView];
workingFrame.origin.x = workingFrame.origin.x + 320;
}
workingFrame.size.width = workingFrame.origin.x;
[scrollview setContentSize:workingFrame.size];
workingFrame.origin.x = 0;
workingFrame.origin.y = 0;
workingFrame.size.width = 320;
workingFrame.size.height = 480;
}
iCodeBlogXMLImagesViewController.m
parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://losectrl-gaincommand.com/iCodeBlogHelper/Tutorial3/iCodeBlogImageXMLB.xml"]];
- Posted by Collin on 19 Jun 2009 in Interface Builder, Uncategorized, objective-c
- Digg |
- Del.icio.us |
- Stumble |
- 18 Comments »
Custom UITableViewCell Using Interface Builder
Hey everyone, welcome to my first of many screencasts coming in the next few weeks. Today I am going to show you how to layout a UITableViewCell in Interface Builder and have a UITableView populate with those type of cells. I am adopting a new structure for my screencasts which will be 5 or so mintues of keynote slides giving background info followed by 20 - 25 mintues of step by step development. The entire video will be directly below this paragraph, but scrolling down you will see a text based step by step of the whole tutorial as well. Hope you guys enjoy.
Skill Level MEDIUM
Here is a link to the screencast to watch. We are working on getting an embedded version in, but I figure this is basically just as functional. Have fun!
Custom UITableViewCell Screencast Video
Source Code
Available Here
Background Information











Building The App
Step 1

This step shouldn’t require any extra information.
Step 2


Step 3

In CustomTableCellTutorialViewController.m you must define the two required UITableViewDataSource methods. These methods will fill up the table view with data. For now we will put in dummy data just to make sure all of our connections are working.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @”Cell”;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[cell setText:[NSString stringWithFormat:@"I am cell %d", indexPath.row]];
return cell;
}
Step 4

Here you will need to be in xCode and go to File -> New File…
Select Objective C Class and make sure it is a UITableViewCell subclass, depending on your version of the SDK selecting this will differ. Look around and you will find it, call it iCodeBlogCustomCell. With this done enter these IBOutlets in the iCodeBlogCustomCell.h file enter the following IBOutlets:
IBOutlet UILabel *articleName;
IBOutlet UILabel *authorName;
IBOutlet UILabel *date;
IBOutlet UIImageView *imageView;
IBOutlet UIView *viewForBackground;
Add the @property and synthesize them in the main.
Step 5

This step does not require and code but does require a lot of work in Interface Builder. I highly recommend you watch the screencast to see the step by step procedure here. Essentially what I do is create a new View XIB file. Opening this, I delete the standard UIView in the XIB and drag a UITableViewCell from my library into my document window. I assign the UITableViewCell to be of type iCodeBlogCustomCell. With this done layout the interface with the proper elements and hook them up by right clicking on the UITableViewCell in the document window.
Step 6

This is where the real magic is. We are going to return to CustomTableCellTutorialViewController.m and edit the UITableViewDataSource methods we implemented earlier. The code I use has me putting in 4 separate PNG files that I add to my project. You can find your own to put inside the cells. Make sure the UIImageView inside the cell is set for Aspect Fit so you don’t have to worry about resizing the images. The functions should be changed to be:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @”iCodeBlogCustomCell”;
iCodeBlogCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSLog(@”New Cell Made”);
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@”iCodeBlogCustomCell” owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[iCodeBlogCustomCell class]])
{
cell = (iCodeBlogCustomCell *)currentObject;
break;
}
}
}
if(indexPath.row % 4 == 0)
{
[[cell authorName] setText:@”Collin Ruffenach”];
[[cell articleName] setText:@”Test Article 1″];
[[cell date] setText:@”May 5th, 2009″];
[[cell imageView] setImage:[UIImage imageNamed:@"1.png"]];
}
else if(indexPath.row % 4 == 1)
{
[[cell authorName] setText:@”Steve Jobs”];
[[cell articleName] setText:@”Why iPhone will rule the world”];
[[cell date] setText:@”May 5th, 2010″];
[[cell imageView] setImage:[UIImage imageNamed:@"2.png"]];
}
else if(indexPath.row % 4 == 2)
{
[[cell authorName] setText:@”The Woz”];
[[cell articleName] setText:@”Why I’m coming back to Apple”];
[[cell date] setText:@”May 5th, 2012″];
[[cell imageView] setImage:[UIImage imageNamed:@"3.png"]];
}
else if(indexPath.row % 4 == 3)
{
[[cell authorName] setText:@”Aaron Hillegass”];
[[cell articleName] setText:@”Cocoa: A Brief Introduction”];
[[cell date] setText:@”May 5th, 2004″];
[[cell imageView] setImage:[UIImage imageNamed:@"4.png"]];
}
return cell;
}
The End
So that is it for my first new post. I will be doing many more. Let me know your thoughts on this format in the comments. If you see anything organization wise that you think should be changed/add/removed let me know. Good Luck!
- Posted by Collin on 24 May 2009 in Interface Builder, Uncategorized, iPhone Articles, iPhone Programming Tutorials, iphone, objective-c
- Digg |
- Del.icio.us |
- Stumble |
- 33 Comments »
iPhone Coding - Learning About UIWebViews by Creating a Web Browser
Wow! It has been a long time since my last tutorial… As I wrote in my last post, I had to take a break due to my wife having our baby. But, now I’m back and have a great tutorial for you guys.
Today I will be showing you how to work with a UIWebview to create a basic web browser. Here is a screenshot of the app we are going to create.

Create a View-Based Application
Ok, so let’s get started. Start by opening up Xcode and click File -> New Project. Next select View-Based Application and click Choose… Name this project something like iCodeBrowser and click Save.


Now we are ready to begin coding…
Create IBOutlets and IBActions
Before we create the interface for our web browser, we need to establish the IBOutles and Actions to interface with the UI elements in code. Start by opening up iCodeBrowserViewController.h and add the following code:

Let’s take a look at this code line by line. The first thing we added was the <UIWebViewDelegate> to the end of our interface declaration. This is telling the app that this class will be the delegate for our UIWebview.
What does it mean to be the delegate you ask? Great question… A delegate is like a handler. It is responsible for implementing certain methods in order to handle events sent by the object they are the delegate for. So in our example, we are simply saying that we will implement some of the functionality of the UIWebView. This is needed so we can capture certain actions of the UIWebView such as a click on a link or so we can tell when a page has started/finished loading. If it’s still unclear, ask me clarifying questions in the comments section.
Next, we see our 3 lines of declaring IBOutlets. These are the UI elements that we will be interacting with. In case you didn’t know, the UIActivityIndicator is the little spinner/loading animation that you see on various apps when content is loading. We will be using this to show that a page is currently loading.
Following this code, there are 3 IBActions. IBActions are functions that get called in response to a user interaction with the application (such as tapping a button). For our basic browser, we are only offering 3 types of functionality. gotoAddress which will take a user to the address they type in the address bar and goBack/Forward should be pretty self explanatory.
Creating the User Interface
Now, let’s create the interface using Interface Builder. I am going to be showing you how to do this in the video below.
Implementing the IBActions
Now that we have our interface, let’s make the app function. We need to implement our methods. Open up iCodeBrowserViewController.m and add the following code.
We need to synthesize our properties to allow us to interact with them. Synthesizing automatically creates “getter” and “setter” methods for our properties. Next, let’s implement the viewDidLoad method. This is where we will be loading our “homepage”. Add the following code to the viewDidLoad method.

The viewDidLoad method gets called automatically by our application whenever this view first loads. We can know for sure that it will get called, so we can put our initialization code here.
The first thing we see is the urlAddress string. This will be our “homepage”. You can change this to any address you wish to start with. Next, we build a URL object with our string. We need to do this so we can make a web request. Following this, we build our web request and load it into the webView. This will display the homepage inside of our webview. Finally, we set the text of the address bar to the homepage address. This part is more for aesthetics to let the user know what page they are on.
Next, we implement the method that we connected to the UITextField’s DidEndOnExit method gotoAddress. Add the following code:

This is similar to the code we wrote in the viewDidLoad method, except for the fact that we are getting our URL string from the address bar. This method gets called when the user presses the “Go” button on the keyboard. The last thing to note here is we call the [addressBar resignFirstResponder] method. This simply tells the app to hide the keyboard when this method gets called.
The implementation of our Back and Forward methods are pretty easy. Go ahead and add the following code.

UIWebViews are pretty cool because of the functionality they offer us built right in to them. We simply call [webView goBAck] to go back and [webView goForward] to go forward. This greatly simplifies the interactions with the webview. If we were to code that functionality from scratch, we would have to create a stack of URLs and continually push and pop them off the stack to keep track of where we need to go. Thanks Apple for not making us implement this.
Finally, we need to implement the delegate methods for UIWebview. These methods allow us to write our own code to respond to actions by the UIWebview. The first methods we will implement are the webViewDidStartLoad and the webViewDidFinishLoad methods. We will use these to show and hide the activity indicator. Add the following code:

So when the request is first made for a ULR (before the page starts loading) the webViewDidStartLoad method gets called automatically. We use this opportunity to start our activity indicator to let the user know the page is loading. If you don’t have something like this, it simply feels like the app is frozen when in fact, it’s just loading the page. Finally, the webViewDidFinishLoad method gets called when the page is fully loaded. After this, we can stop the indicator (and it automatically hides itself).
The very last thing we need to do is define what happens when a user clicks on a link. Add the following method:

This method gets called automatically whenever the user clicks a link. This method can be very useful if you want to make a native iPhone application that integrates with a web app. You can use this method to trap the user’s clicks and have your application respond to web links that get clicked. In our case, we need it to do 2 things. The first is to set the text of the address bar to the URL of the link that was clicked on and to load that address into the webview.
One thing to make note of: We do a check to see if the URL scheme is “http”. This is to ensure that the user typed http before their URL. You can add an else statement here that auto prepends the http if the user did not add it. This would allow you to type in a url such as “icodeblog.com” rather than having to type “http://www.icodeblog.com”. I chose to omit it for this tutorial.
Remember, all of this added functionality of a UIWebView can only be gotten if you tell your class that it implements the UIWebViewDelegate protocol as we did in our .h file.
The app should be complete! Click on Build and Go to see this baby in action. Remember, you must put “http://” in front of your URL’s.
I hope you have enjoyed this tutorial. If you have any questions or comments, feel free to leave them in the comments section of this post. You can download the source here . Happy iCoding!
- Posted by Brandon on 19 Dec 2008 in Interface Builder, iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
- 48 Comments »
iPhone Programming Tutorial - Animating a Ball Using An NSTimer
I have noticed recently many people wanting to create games for the iPhone and are unsure where to start. A common misconception is that you must use OpenGL ES to create any game with graphics. I am going to show you today how you can do some simple animation by moving a ball around the screen. We will not be using OpenGL ES to move the ball. We will simply be using an NSTimer and a UIImageView.
The code for this could be used in many game applications. Games such as pong, brick breaker, etc… I will soon do an iPhone game programming tutorial series. For now, here is a quick tutorial to get you started and excited…
You will need to download this image for this tutorial:
Here are the steps involved in creating this application:
Start With a View-Based Application
We will not need any navigation components for this app. All we need is a view that we can add a UIImageView to.
Add The Ball Image To Your Project
You can use any image you would like for this. I used my mad skills in Photoshop to create a shiny red ball for you to use. This will be the image that we will be “bouncing” around the screen.
Add An IBOutlet For the Ball
This step is necessary as it allows us the link the ball we add to the view in Interface Builder to the code. This is so we can update the position of the ball at each timestep.
Add The Ball To The View In Interface Builder
All we need to draw the ball on the screen is a UIImageView. Since we added the ball.png file to our project, it should appear in the drop-down in the attributes section of the UIImageView. Also, at this step, we need to connect the UIImageView to the ‘ball’ variable by dragging from ‘new referencing outlet’ in the connection inspector of the UIImageView to the ‘File’s Owner’ object.
Add The Code To Initialize The NSTimer
An NSTimer is very simple to use. It simple requires that you specify an interval (I used .05) and a function to call at each time-step. The function we are calling in this tutorial is the onTimer function. This is a function that we create and will contain the logic to move the ball.
Moving The Ball
This code is all fairly straight forward. First we add the pos.x and pos.y values (14.0 and 7.0) to the center of the ball object this causes the ball to move diagonally. Next we simply check to see if the ball has collided with the wall. If the ball does collide with the wall, we simple reverse the pos.x or the pos.y.
That concludes the animation tutorial. I hope that you go out an make lots of great games after this… Soon, I will start another tutorial series where I we will be creating a full blown game. If you have any suggestions for games, please leave them in the comments. Make sure that they are fun but not too in depth, we need to limit the series. Think in terms of pong, asteroids, etc…
You can download the source code here . If you have any comments or questions, feel free to leave them in the comments of this post. You may also post them in the forums. Happy iCoding!
- Posted by Brandon on 28 Oct 2008 in Interface Builder, Uncategorized, iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
- 69 Comments »
iPhone Programming Tutorial - Using A TabBarView To Switch Between Views
In this tutorial I will show you how to develop a UITabBarController which contains a custom UIView from one of the tabs and a UINavigationController with a UITableView dictated byUISegmentControl in the second tab.
This tutorial was contributed by the user cruffenach. You can check out his website at http://losectrl-gaincommand.com.
If you would like to contribute a tutorial to iCodeBlog.com, contact me brandon@icodeblog.com
The final product of this tutorial should look something like this:
Setting up the User Interface
The first thing we need to do is open up MainWindow.xib. This will launch interface builder and show what our UITabBarController looks like. In the first tab we see a custom UIView that can be changed however we like, but we are more concerned about the second tab.
Clicking on the TabBarController within the instance window of interface builder and then looking to the Inspector will let us set the type of view controller which each tab will be displaying. The first tab uses a ViewController, and for the second tab we want to use a Navigation Controller type because we will be utilizing the navigation bar to hold our segmented control.
Once in the second tab, we will drag a UISegmentedControl out of our library and onto the navigation bar. The UISegmentedControl will change its look depending on the context you place it in. Here we will essentially be making the TitleView of the NavigationItem a UISegmentedView. This will be important when we get into our code.
With that done, we click on the view of the second tab and set it to be identified as a SegmentedTableViewController or type UITableViewController. We will create that class later in xCode. With that set we drag in a UITableView and connect its DataSource and Delegate methods to our view controller which has now been defined as SegmentedTableViewController. That is all we need to do in interface builder.
Going into xCode we do not need to modify any of the generated classes, however we do need to create a new one. Hit Apple + N and create a new UITableViewController called SegmentedTableViewController. This class will have the datasource methods for a UITableView all ready.
In this class we are going to need an int called selectedSegment, this will be updated to represent which segment is selected. Within the main we need to uncomment the viewDidLoad method and enter the following code.
This code gets the UISegmentedControl from the titleView of the navigationItem, and modifies it to add an action so that when the selected segment changes a method called segmentAction is called. The selectedSegment int is set to the initially selected segment and the titleView is reset with the modified UISegmentedControl.
Next we need to create the method which the UISegmentedControl will call. Here is the code for that method, following the same syntax as a IBAction Method.
This code takes the sender which will be out UISegmentedControl and gets the new selectedSegment from it and sets out variable to that value. Finally it tells the UITableView that something has happened and the data in the table needs to be reloaded.
The final steps is to tell the UITableView that is will be displaying 100 cells and telling the returned cell for each row to have some text which is a product of the selected segment. I chose to have each cell read “I AM CELL (selectedSegment * indexPath.row)”. This essentially means that when segment 0 is selected every cell will read.
I AM CELL 0
When segment 1 is selected the cells will read.
I AM CELL 0
I AM CELL 1
I AM CELL 2
….
When segment 2 is selected the cells will read.
I AM CELL 0
I AM CELL 2
I AM CELL 4
I AM CELL 6
….segment. I chose to
The code to make this happens is…
You can download the source for this tutorial here. icodesegmentcontrol
- Posted by cruffenach on 13 Oct 2008 in Interface Builder, iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
- 36 Comments »

I have noticed recently many people wanting to create games for the iPhone and are unsure where to start. A common misconception is that you must use OpenGL ES to create any game with graphics. I am going to show you today how you can do some simple animation by moving a ball around the screen. We will not be using OpenGL ES to move the ball. We will simply be using an NSTimer and a UIImageView.




