Make Better Things

I like to make better things.

Call SOAP web service from iPhone

Here is my experience with calling SOAP web services from iPhone SDK.

For this tutorial i am using w3school’s CelsiusToFahrenheit SOAP web service example here you can find the docs for this service.

To call a SOAP service first i create a string with the SOAP request as follows.

NSString *soapMessage = @"<?xml version="1.0" encoding="utf-8"?>n"
	"<soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">n"
	"<CelsiusToFahrenheit xmlns="">n"

After creating the SOAP request I create a NSMutableRequest to send this request to server.

 	NSURL *url = [NSURL URLWithString:@""];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue: @"" forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

	if( theConnection )
		webData = [[NSMutableData data] retain];
		NSLog(@"theConnection is NULL");

After firing the request we can collect the XML response in the NSURLConnection’s delegate methods.

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
	[webData setLength: 0];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
	[webData appendData:data];
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
	NSLog(@"ERROR with theConenction");
	[connection release];
	[webData release];
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
	NSLog(@"DONE. Received Bytes: %d", [webData length]);
	NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
	[theXML release];

After collecting the XML response in theXML string in -(void)connectionDidFinishLoading:(NSURLConnection *)connection
we can parse this string using TBXML for any other XML parser you like.