Categories
Articles

XCode 4 IPhone Mountains of the USA Tutorial: Lesson 2 – Load XML Data

<== Lesson 1 || Overview || Lesson 3 ==>

In this lesson you will make a requests for the Mountain data from a web site. The data is returned in an XML format. Then for testing you will display the raw XML on the phone screen and also display the XML data in the XCode console.

Screen With XML Loaded From Web

The main goal is to learn to use the NSURL, NSURLRequest, NSURLConnection and NSMutableData classes.

NSURL defines a URL for XCode. NSURLConnection establishes a connection to a server and manages the data to and from that server. NSURLRequest defines a network request along with data to send. NSMutableData stores any returning data.

When you load data from the web or any indeterminate process, you will want to include an activity indicator. So we will add a UIActivityIndicatorView that is the common activity indicator for Mac applications.

To see the data on the phone screen, we will use the UITextView which is a scrollable text component. In future lessons, we will replace the UITextView with a scrolling list of mountains in the XML data we receive.

You will need a web server to complete this and all future lessons in this tutorial. The tutorials use a web server with PHP that reads a comma delimited file containing the mountain data. The XML that the PHP script returns is included in this post should you not have PHP on your server. I will show you how to use that instead of the provided PHP script. However in future lessons we will want to ask the server for just partial data and we need a program to do that. Keep in mind you can also put the mountain data into a database on the server.

Source Download

  1. Starting XCode Project. This is the lesson 1 project completed.
  2. PHP and CSV Files. Script to read data file and selects by elevation and returns XML.
  3. Mountain XML Data. Alternative to hosting PHP script.
  4. Completed XCode 4 Project

[ad name=”Google Adsense”]

Step 1: MainViewController.h – Define properties and methods.

Download and uncompress the Starting XCode Project file and open in XCode.

Select the MainViewController.h in the project navigation window on the left and add the highlighted lines.

Line 4 is a constant for the URL to the PHP script or the XML file if you choose not to host the PHP script. More on these choices in this post when we get to those files.

The app will enable and disable the UIButton searchButton, so we need to include it for reference in code.

The UIActivityIndicatorView and UITextView are being added and are also referenced from our UI. The UIActivityIndicatorView will need to be hidden and revealed when we are not and are loading data from the server as well starting and ending its animation. So we need to make it an IBOutlet.

The UITextView will be updated with data coming in from the server and so it also needs to be an IBOutlet.

The MSMutableData is needed to capture the data coming in from the server in a raw format.

Your implementation code will call for disabling and enabling the search button and hiding and unhiding the activity indicator in more than one place in the code. Line 26 defines a method you will use so you do not have to repeat this UI state changing code in more than one place. The method receives an int parameter to define the state of the UI components. You will define their values in the implementation code.

//
//
//
#define kTextURL    @"http://YOUR_DOMAIN/PATH_IF_ANY_TO_SCRIPT/PHP_SCRIPT_OR_XML_FILE"

#import &lt;uikit uikit.h=""&gt;&lt;/uikit&gt;

@interface MainViewController : UIViewController
{
    UIButton                *searchButton;
    UIActivityIndicatorView *activityIndicator;
    UITextView              *resultsTextView;

    NSURLConnection         *urlConnection;
    NSMutableData           *receivedData;

}
@property (nonatomic, retain) IBOutlet UIButton                 *searchButton;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView  *activityIndicator;
@property (nonatomic, retain) IBOutlet UITextView               *resultsTextView;

@property (nonatomic, retain) NSURLConnection *urlConnection;
@property (nonatomic, retain) NSMutableData *receivedData;

-(IBAction) startSearch:(id)sender;
- (void) setUIState:(int)uiState;
@end

Step 2: MainViewController.m – Add Properties and Constants

This step basically is the implementation housekeeping prerequisites.

You add the getter and setters for the properties on lines 4 to 9 using synthesize.

Lines 12 and 14 provide constants for states of the view that are used in the setUIState method we defined in the last step. Those places in the code can make the code more readable when calling the setUIState.

#import "MainViewController.h"

@implementation MainViewController
@synthesize searchButton;
@synthesize activityIndicator;
@synthesize resultsTextView;

@synthesize urlConnection;
@synthesize receivedData;

// State is loading data. Used to set view.
static const int LOADING_STATE = 1;
// State is active. Used to set view.
static const int ACTIVE_STATE = 0;

Step 3: MainViewController.m – Memory Management Housekeeping

Add the memory release for the searchButton, activityIndicator, activityIndicator, resultsTextView, urlConnection and receivedData in the dealloc method.


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [searchButton release];
    [activityIndicator release];
    [resultsTextView release];
    [urlConnection release];
    [receivedData release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

Step 4: MainViewController.m – Navigation Top Bar Title Updated

On line 47 you might want to update the title so you are not confused when viewing the app.

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"USA Mountains Lesson 2"];
}

Step 5: MainViewController.m – More Memory Management

In the viewDidUnload method add these lines to release the subviews you are going to link to this view in the UI.

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.searchButton = nil;
    self.activityIndicator = nil;
    self.resultsTextView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

Step 6: MainViewController.m – Update the startSearch Method to Fetch Server Data

The startSearch method is already linked to our searchButton from the last tutorial. You have the code below to get the UI in the state for loading in progress, to make a request to the data source on the server and take needed steps based on the success or failure of that connection.

Line 69 is calling a method you will add in the next step to set the UI state. Your constant LOADING_STATE was defined in the last step.

Line 71 creates a NSString for the URL. In a future lesson you are going to concatenate a parameter to send along with the URL and now this line is ready for that.

[ad name=”Google Adsense”]

The NSURLRequest object named req is created on line 74.

The instance object named urlConnection on line 77 is your NSURLConnection. It does all the work for communicating with the server.

You see on line 77 it is using our NSURLRequest req object and also sending the delegate message to make this class, self, its delegate. That means urlConnection can call NSURLConnection methods you add to this class to take action needed to handle notifications such as successful completion or failure.

For this lesson you need to add four methods to handle the NSURLConnection messages didReceiveResponse, didReceiveData, didFailWithError and connectionDidFinishLoading. You will do that just after creating our setUIState method.

Lines 79 to 83 handle a successful connection. A NSMutableData object is created and assigned to the class receivedData NSMutableData object that in later code you will convert to readable XML for display.

Should the connection fail, lines 85 to 97 display a UIAlertView with the error information. Generally you will want to change that to something more meaningful to the user.

#pragma mark - UI Interface
-(IBAction) startSearch:(id)sender
{
    NSLog(@"startSearch");
     // Change UI to loading state
    [self setUIState:LOADING_STATE];
    // Create the URL which would be http://YOUR_DOMAIN_NAME/PATH_IF_ANY_TO/get_usa_mountain_data.php?elevation=12000
    NSString *urlAsString = [NSString stringWithFormat:@"%@", kTextURL ];

    NSLog(@"urlAsString: %@",urlAsString );
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlAsString]];
    // Create the NSURLConnection con object with the NSURLRequest req object
    // and make this MountainsEx01ViewController the delegate.
    urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    // Connection successful
    if (urlConnection) {
        NSMutableData *data = [[NSMutableData alloc] init];
        self.receivedData=data;
        [data release];
    }
    // Bad news, connection failed.
    else
    {
        UIAlertView *alert = [
                              [UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"Error", @"Error")
                              message:NSLocalizedString(@"Error connecting to remote server", @"Error connecting to remote server")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(@"Bummer", @"Bummer")
                              otherButtonTitles:nil
                              ];
        [alert show];
        [alert release];
    }
    [req release];

}

Step 7: MainViewController.m – Create the UI State Setting Method setUIState

This is your custom method to set the states of the UI components.

The UIButton has an alpha and enabled property. For your UIButton searchButtonobject, the alpha value is toggled between 50% and 100% and its enabled state is also toggled between true and false.

The UIActivityIndicatorView has methods on lines 108 and 116 for starting and stopping their animation. There is also a property hidesWhenStopped that you will set in the UI design that handles the hiding and showing of our UIActivityIndicator.

-(void) setUIState:(int)uiState;
{
    // Set view state to animating.
    if (uiState == LOADING_STATE)
    {
        searchButton.enabled = false;
        searchButton.alpha = 0.5f;
        [activityIndicator startAnimating];

    }
    // Set view state to not animating.
    else if (uiState == ACTIVE_STATE)
    {
        searchButton.enabled = true;
        searchButton.alpha = 1.0f;
        [activityIndicator stopAnimating];
    }
}

Step 8: MainViewController.m – Clear Received Data When Connection Is Established

You learned about pragma marks in the last lesson. You have 4 NSURLConnection related methods to add and this mark on line 119 is an easy way in XCode to get to where you are placing them in the code.

The connection didReceiveResponse method occurs when a connection is established. When that happens, your data communication starts over. To be on the safe side of it occurring more than once, you clear the NSMutableData object from any previous incomplete attempts. Consider this a boilerplate block you always include in code.

#pragma mark - NSURLConnection Callbacks
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

Step 9: MainViewController.m – Accumulate Data Being Received

The NSURLConnection calls the connection didReceiveData method as data arrives and is ready for use. This is called as often as needed depending on the amount of data. The code you need here is to append the data received to your NSMutableData object.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

Step 10: MainViewController.m – Handle Network Connection Failure

The connection didFailWithError NSURLConnection call back method is where you handled the failure of the data transmission. In your case the code displays a UIAlertView with information from the NSError class error object passed in for learning purposes. A better user error should be considered for a released app.

You can use the NSError class to take different action based on the type of error. This is over the scope of this tutorial.

[ad name=”Google Adsense”]

There is some housekeeping such as calling the connection object release method and terminating the NSMutableData receivedData property.

The last line of code calls the sertUIState method with the ACTIVE_STATE value so the UI again appears available for another search.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    self.receivedData = nil; 

    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Error"
                          message:[NSString stringWithFormat:@"Connection failed! Error - %@ (URL: %@)", [error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]
                          delegate:self
                          cancelButtonTitle:@"Bummer"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    // Change UI to active state
    [self setUIState:ACTIVE_STATE];
}

Step 11: MainViewController.m – Handle Network Connection Successful Completion

This final method is called when all the data is successfully loaded. The NSMutableData receivedData object is converted to a NSString on line 147.

On line 151 the UITextView text property resultsTextView is set to the data as a NSString. One the previous line the same is displayed in the XCode console window.

After that the NSURLConnection connection variable is released and the receivedData NSMutable object is truncated.

Your last line has the same task of setting the UI back to a state that the user can search again.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Convert receivedData to NSString.
    NSString *receivedDataAsString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    // Trace receivedData
    NSLog(@"%s - %@", __FUNCTION__, receivedDataAsString);
    resultsTextView.text = receivedDataAsString;
    [receivedDataAsString release];

    // Connection resources release.
    [connection release];
    self.receivedData = nil;
    // Change UI to active state
    [self setUIState:ACTIVE_STATE];
}

Step 12: MainViewController.xib – Add the Activity Indicator

Open the MainViewController.xib in the Project navigator and drag an Activity Indicator from the Objects library in the bottom right to place it under the button with the Search label.

Activity Indicator View

Be sure you keep the Activity Indicator you placed selected while completing the next three tasks.

Select the size panel in the top right and set the x and y values as shown here.

Activity Indicator Size Inspector

Select the Properties inspector and set the style to Large White and check the Behavior Hides When Stopped.

Activity Indicator Properties

In the Connections Inspector panel drag from the “New Referencing Outlet” in the “Referencing Outlets” group to the File Owner’s icon and release the mouse. Then select activityIndicator. You defined activityIndicator in your MainViewController code as a UIActivityIndicatorView.

Here is how the Connections Inspector will look when you are done.

Activity Indicator Connection Inspector

Step 13: MainViewController.xib – Add the TextView

You are adding a TextView that in a future tutorial you replace with a TableView. So there is no need to get heavily invested in how it looks.

Now drag a TextView from the Objects library in the bottom right to place it under the button with the Activity Indicator.

Text View

Keep the TextView you placed selected while completing the next two tasks.

Select the size panel in the top right and set the X, Y, Width and Height values as shown here.

Text View Size Inspector

In the Connections Inspector panel drag from the “New Referencing Outlet” in the “Referencing Outlets” group to the File Owner’s icon and release the mouse. Then select resultsTextView defined activityIndicator in your MainViewController code as a UITextView.

Your Connections Inspector should appear as follows.

Text View Connection Inspector

Step 14: MainViewController.xib – Review the Changes

First you can check the layout looking as follows.

MainViewController Design Window Complete

If you select the Connections inspector and then the File Owner’s icon you should see the following. If so you are good to go.

File Owner’s Connection Inspector

Step 15: PHP Server Script or XML File

This IPhone app loads XML data from a server. The Source Download includes an XML file you can use for this lesson.

However, the longer term of the Tutorial will request a query of the data from the server and at that point you can use the PHP script provided. I suggest you use that with this lesson so you are set up. But if you do not have a PHP script enabled server, you can use the XML file for a few more lessons.

Detailing how the PHP script works is beyond the scope of this tutorial. However what you should know it reads a CSV file. Here is a snippet of the file. The name used in the PHP script is mountain_data.csv.

Mount McKinley,20320, 63.0690,-151.00063
Mount Saint Elias,18008,60.2927,-140.9307
Mount Foraker,17400,62.9605,-151.3992

Then the PHP script returns XML. This is a snippet of what the XML data looks like when returned.

&lt;!--?xml version="1.0" encoding="UTF-8"?--&gt;
&lt;mountains source="http://en.wikipedia.org/wiki/Table_of_the_highest_major_summits_of_the_United_States" elevation_min="12000" count="100"&gt;
  &lt;mountain_item id="1" name="Mount McKinley" elevation="20320" lat=" 63.0690" lon="-151.00063"&gt;
  &lt;mountain_item id="2" name="Mount Saint Elias" elevation="18008" lat="60.2927" lon="-140.9307"&gt;
  &lt;mountain_item id="3" name="Mount Foraker" elevation="17400" lat="62.9605" lon="-151.3992"&gt;
&lt;/mountain_item&gt;&lt;/mountain_item&gt;&lt;/mountain_item&gt;&lt;/mountains&gt;

This XML you will learn to parse in a future tutorial.

This is the PHP script. The name I used for the script was get_mountain_data.php. You can name it what you like.

&lt;!--?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");
// XML to return.
$xml = '';
// Counter for number of mountains returned.
$mountain_count = 0;
// Filter mountains equal to or above this value. 
$elevation_min = 12000;
// Check for elevation parameter as a integer.
if ($_REQUEST['elevation_min'] &amp;&amp; intval($_REQUEST['elevation_min']))
{
	$elevation_min = intval( $_REQUEST['elevation_min']);
}
// Each element contains data for one mountain.
$mountains = array();
// Read a CVS file containing mountain data.
$mountain_data_lines = file('mountain_data.csv');
// Each line read .
foreach($mountain_data_lines as $line) 
{
	// Strip newline at end of line and break line by comma delimiter and 
	// append to $mountains.
	$mountains[] = explode( ',', rtrim($line));
}
// Each mountain.
foreach ($mountains as $value)
{
	// Mountain elevation equals or exceeds the filter value.
	if ( intval($value[1]) --&gt;= $elevation_min  )
	{
		$mountain_count++;
		// Create the mountain_item node.
		$xml .= '&lt;mountain_item ';="" $xml="" .="id = &amp;quot;" $mountain_count="" '"="" $value[0]="" $value[1]="" $value[2]="" $value[3]="" ;&lt;="" p=""&gt;
&lt;/mountain_item&gt;

	}
}
// Add mountains close node.
$xml .= '';
// Create mountains open node.
$xml_mountains = '&lt;mountains ';="" $xml_mountains="" .="source = &amp;quot;http://en.wikipedia.org/wiki/Table_of_the_highest_major_summits_of_the_United_States&amp;quot; " ;="" $elevation_min="" '"="" $mountain_count="" ;&lt;br=""&gt;
// Add mountains open node.
$xml = $xml_mountains . $xml;
// Return xml
echo $xml;
?&amp;gt;

<== Lesson 1 || Overview || Lesson 3 ==>