Consuming SOAP web services from iOS (Objective-C)

Hi,

In this post, I’ll show you how to consume a SOAP web service (asmx web service) from iOS. It’s pretty easy to start off with.

There are many links that talk about the use of many frameworks like ASIHttp framework, JSON Framework, wsdl2objc tool, etc. But for the purpose of this post, I would like to keep it simple (KISS! ;-)) Those frameworks are basically used for consuming web service methods that are more complex and those that return JSON response or things like that.

More on those later. For now, let’s concentrate on consuming a very basic ASMX web service hosted by w3schools.org, Temperature conversion web service.

As you can see, this web service exposes two methods: Convert a given temperature from Celsius to Fahrenheit and vice versa. In this post, let’s consume the first one (Celsius to Fahrenheit method).

The steps to follow for consuming the service from XCODE are given below:

  1. Create the request SOAP Envelope message as string
  2. Create a request to the URL
  3. Add required request header elements
  4. Initiate the request
  5. Implement connection delegate methods
  6. Parse the response.

For creating the soap request envelope message, open the method definition in the browser and copy-paste the request string as shown in the page. A sample is shown below:

soap Message

Note the format specifier in the middle of the soap message. That is to take the value entered by the user from the text field.

Celsius

Next step is to create a request to the URL of the web service. Sample code is shown below:

Request

Next, add the required header elements to the request object. You can find out what header elements are required in the message by looking at the sample request objects shown in the webpage of the service’s method. Sample code shown below:

Headers

Finally, set the body of the request by converting the soapMessage to bytes (shown in the last step above).

Next step is to implement the NSURLConnection delegate methods in the application. These methods are used to implement functionality at different stages of the request. A sample of the methods is shown below:

Connection Methods

The code of the connection methods is given below:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.webResponseData  setLength:0];
}

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

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Some error in your Connection. Please try again.");
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Received %d Bytes", [webResponseData length]);
    NSString *theXML = [[NSString alloc] initWithBytes:
                        [webResponseData mutableBytes] length:[webResponseData length] encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",theXML);
    
    //now parsing the xml
    
    NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData];
    
    //setting delegate of XML parser to self
    xmlParser.delegate = self;
    
    // Run the parser
    @try{
        BOOL parsingResult = [xmlParser parse];
        NSLog(@"parsing result = %hhd",parsingResult);
    }
    @catch (NSException* exception)
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Server Error" message:[exception reason] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

In the last method, you can see that we have written some code to parse the response received from the web service.
Now, to enable our application to parse the response XML, we need to indicate that our app implements the NSXmlParserDelegate interface.

For this purpose, specify the same in the interface file as shown below:

interface

Now, the next step is to implement the NSXmlParserDelegate methods. It has 3 methods:

  1. didStartElement
  2. foundCharacters
  3. didEndElement

The code of the above methods is given below:


//Implement the NSXmlParserDelegate methods
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:
(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    currentElement = elementName;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([currentElement isEqualToString:@"CelsiusToFahrenheitResult"]) {
        self.resultLabel.text = string;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"Parsed Element : %@", currentElement);
}


The foundCharacters method is called when an XML tag is encountered that has some characters between the start and end tag. In our case, the response is wrapped between the CelsiusToFahrenheitResult tag. The characters that are found between the start and end tag are stored in the NSString variable string. Hence the code. The result string found is assigned to the result label on the screen.

When you put all the required pieces of the code together and run the app, you get this result.

result

When the user enters the celsius value in the text box and presses the button, the web service is called and the resultant xml response is parsed and the resulting value is displayed on to the screen.

I have attached the complete sample application source code here. Do have a look. You can download a zip copy of the same there from the bottom right of the page.

Hope this helps!

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET, iOS and tagged , , , , , , , , , , , , . Bookmark the permalink.

8 Responses to Consuming SOAP web services from iOS (Objective-C)

  1. allensmith2 says:

    Thanks for your sharing,i learn a lot from your post.There is a lot of very useful knowledge in your post.I enjoy reading it and hope to see more.Can you write more about this topic?I am very interested in it.Waiting for your new post.
    add qrcode in c#.net

    • Amogh Natu says:

      Thanks for the positive feedback. I’m glad it has helped you. Please share it if you’ve found it useful.
      As for other posts, please subscribe to my blog and you would be automatically notified of new posts that I’m posting soon 🙂

  2. Arturo says:

    Thanks, this is very helpful, but i can not apply in my own WS, i have one question? there is any differences if i do no not have the last section of the WS call HTTP Post?
    if there is a differences, there are another way to make this request?

    thanks! 🙂

  3. Thanks for the article, but now apple need HTTPS service. W3c dont have https. Can you give a suggestion for test?

  4. vs says:

    is that possible to call https soap service in ios?

  5. Pingback: How To Make A Soap Call In Objective-c | Gogoodskh

  6. sasha says:

    hello,

    Can you show it with swift?

  7. Himanshu says:

    The tutorial is incomplete , you made the NSURLRequest but din’t tell how to initiate the request, just after that you explained delegates.

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s