RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Consuming XML Web Services in iPhone Applications : Page 3

Find out the various ways you can call web services and parse responses from your iPhone applications to give your applications a huge range of data sources.


Consuming Web Services in iPhone Applications

With all the background explained, you can now tackle the exciting task of consuming a web service in your iPhone application! First, you need to learn to communicate with the web service using SOAP.

Using Xcode, create a View-based Application project and name it WebServices. Double-click the WebServicesViewController.xib file to open it in Interface Builder. Double-click on the View item and populate it with the views listed below and shown in Figure 3:

  • Label
  • Text Field
  • Round Rect Button
  • Activity Indicator
Figure 3. Building a Web Service Client: Populate the View window with the various views shown here.

Back in Xcode, edit the WebServicesViewController.h file and add the statements shown in bold in the following code:

#import <UIKit/UIKit.h>
@interface WebServicesViewController : UIViewController {
    IBOutlet UITextField *ipAddress;
    IBOutlet UIActivityIndicatorView *activityIndicator;
    //---web service access---
    NSMutableData *webData;
    NSMutableString *soapResults;
    NSURLConnection *conn;
@property (nonatomic, retain) UITextField *ipAddress;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
- (IBAction)buttonClicked:(id)sender;

Save the file and return to Interface Builder, where you need to perform the following actions:

  • Control-click on the File’s Owner item and drag it over the Text Field view. Select ipAddress.
  • Control-click on the File’s Owner item and drag it over the Activity Indicator view. Select activityIndicator.
  • Control-click the Rounded Rect Button view and drag it over the File’s Owner item. Select the buttonClicked: action.
Figure 4. Completed Connections: The figure shows the outlet connections and actions for the File’s Owner item.

If you right-click on the File’s Owner item now, you should see the connections as shown in Figure 4.

In the WebServicesViewController.m file, first create the setters and getters for the Text Field and Activity Indicator properties:

import "WebServicesViewController.h"
@implementation WebServicesViewController
@synthesize ipAddress;
@synthesize activityIndicator;

Next, define the buttonClicked: method (see Listing 1), which will formulate the SOAP request packet and send it over to the web service.

Let’s spend some time examining what you just did by adding the code in Listing 1. First, you create the SOAP request packet:

    NSString *soapMsg = 
        [NSString stringWithFormat:
            @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
             "</soap:Envelope>",  ipAddress.text

Next, you create a URL load request object using instances of the NSMutableURLRequest and NSURL objects:

    NSURL *url = [NSURL URLWithString: 
    NSMutableURLRequest *req = 
      [NSMutableURLRequest requestWithURL:url];

You then populate the request object with the various headers, such as Content-Type, SOAPAction, and Content-Length. You also set the HTTP method and HTTP body:

    NSString *msgLength = 
      [NSString stringWithFormat:@"%d", [soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8"  
    [req addValue:@"http://www.ecubicle.net/webservices/FindCountryAsXml" 
    [req addValue:msgLength 
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

Before you make the actual request to the web service, you get the Activity Indicator view to start animating, thus providing a visual feedback to the user that the application is waiting for a response from the web service:

[activityIndicator startAnimating];

To establish the connection with the web service, you use the NSURLConnection class together with the request object just created:

   conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
   if (conn) {
      webData = [[NSMutableData data] retain];

The NSURLConnection object will now send the request to the web service, and will asynchronously call various methods (which you will define next) as it receives responses from the web service. The data method of the NSMutableData class returns an empty data object that represents a wrapper for byte buffers, which you will use to receive incoming data from the web service.

When data starts streaming in from the web service, the connection:didReceiveResponse: method will be called, which you need to implement here:

-(void) connection:(NSURLConnection *) connection 
didReceiveResponse:(NSURLResponse *) response {
   [webData setLength: 0];

Note that the preceding code initializes the length of webData to 0. As the data progressively comes in from the web service, the connection:didReceiveData: method will be called repeatedly. You use the method to append the data received to the webData object:

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

If there is an error during the transmission, the connection:didFailWithError: method will be called:

-(void) connection:(NSURLConnection *) connection 
didFailWithError:(NSError *) error {
[webData release];
    [connection release];

When the connection has finished and succeeded in downloading the response, the connectionDidFinishLoading: method will be called:

-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSString *theXML = [[NSString alloc] 
                        initWithBytes: [webData mutableBytes] 
                        length:[webData length] 
    //---shows the XML---
    [theXML release];    
    [activityIndicator stopAnimating];    
    [connection release];
    [webData release];

For this example, you simply print the XML response received from the web service to the Debugger Console window and then stop the Activity Indicator view from animating.

Finally, release all the properties and objects in the dealloc method:

- (void)dealloc {    
    [ipAddress release];
    [activityIndicator release];
    [xmlParser release];
    [soapResults release];
    [super dealloc];

That’s it! Press Command-R to test the application on the iPhone Simulator. Enter the IP address in the Text Field, and then tap the Find Country button. In Xcode, press Shift-Command-R to open the Debugger Console window. You'll see that the following request was sent to the web service:

<?xml version="1.0" encoding="utf-8"?>
      <FindCountryAsXml xmlns="http://www.ecubicle.net/webservices/">

The web service SOAP response contains "United States."

<?xml version="1.0" encoding="utf-8"?>
            <IPCountryService xmlns="">
               <Country>United States</Country>

The response from the web service indicates that you have managed to communicate with the web service. The problem now is how to parse the XML to extract the relevant result that you want. In this case, the result you want is encapsulated in the <Country> element. The last section of this article shows how to parse the XML response, but for now, let’s see what you should do if you want to use the HTTP GET and HTTP POST methods, as opposed to using the SOAP method to talk to the web service.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date