Web services allows to transfer the data between different platforms. There are scenarios where iOS application needs to send or receive data using an external web service. In this article we are going to learn how to use consume a .NET web service from within an iOS application.

NOTE: For this article we will be using MonoDevelop framework to create our .NET project. You might notice that URLS for invoking the web methods differ from when using Visual Studio vs MonoDevelop.

Downloading Libraries for iOS Application:

We are going to utilize a couple of third party libraries in our application. Take a look at the following list:

1) ASIHTTPRequest

This library is used for making HTTP requests using iOS framework. Copy all the files in the classes folder and in the External folder to a new folder in your iOS application.

2) JSON Framework

This library is used to convert the string into the JSON object. Copy all the files in the Classes folder to a new folder in your iOS application.

Apart from the above two libraries we are also going to use a number of built-in frameworks. Add the following frameworks to your project:

1) CFNetwork.framework
2) SystemConfiguration.framework
3) MobileCoreServices.framework
4) libz.1.2.3.dylib

Creating a .NET Web Service:

We will start by creating a very simple HelloWorld service. Add a new web service file to your project and name is "NotificationService.asmx". The "HelloWorld" web method is shown below:

1public class NotificationService : System.Web.Services.WebService
2    {
3        [WebMethod]
4        public string HelloWorld()
5        {
6            return "Hello World";
7        }
8         
9    }


Pretty simple right!

Creating an iOS Client:

Our iOS client will consist of a button which when clicked will make a request to the HelloWorld web method of the NotificationService. The button click event is shown below:

01-(IBAction)submitButtonClicked:(id)sender
02{
03 
04    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/NotificationService.asmx/HelloWorld?"];
05    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
06    [request setRequestMethod:@"POST"];
07    [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"];
08       
09    [request setDelegate:self];
10    [request startAsynchronous];     
11}


The URL points to the "HelloWorld" web method which will be invoked when the button is clicked. The requestFinished and requestFailed methods are implemented below which are called depending on the result of invocation.

01- (void)requestFinished:(ASIHTTPRequest *)request
02{
03    NSLog(@"status code %d",request.responseStatusCode);
04     
05    if(request.responseStatusCode == 200)
06    {
07        NSLog(@"success");
08        NSString *responseString = [request responseString];
09        NSLog(@"%@",responseString);
10    }
11     
12    NSLog(@"request finished");
13}
14 
15- (void)requestFailed:(ASIHTTPRequest *)request
16{    
17    NSError *error = [request error];
18    NSLog(@"%@",error.localizedDescription);
19     
20}


When you run the iOS application you will get the following in your console.

1<?xml version="1.0" encoding="utf-8"?>
2<string xmlns="http://tempuri.org/">Hello World</string>


This ensures that the web method "HelloWorld" was called from the iOS application and it returned string "Hello World" to the client. In the next section we are going to demonstrate how to call a SOAP web service with parameters.

Invoking Web Service with Parameters:

Calling parameter less web method is quite easy. In this section we are going to call a web service which accepts multiple parameters. The web service implementation is shown below:

1[WebMethod]
2        public string Greet(string deviceToken,string userName)
3        {
4            return deviceToken + ":" + userName;
5        }


The above web method "Greet" takes two parameters namely deviceToken and userName and returns a concatenation between the two parameters. In order to call this web method from an iOS we will need to construct a SOAP envelope. The implementation is shown below:

01-(IBAction)submitButtonClicked:(id)sender
02{
03       NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/NotificationService.asmx"];
04    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
05    [request setRequestMethod:@"POST"];
06    [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"];
07    [request addRequestHeader:@"SOAPAction" value:@"http://tempuri.org/HelloWorld"];
08     
09     
10    NSString *soapMessage = [NSString stringWithFormat:
11                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12                             
13 "<soap:Envelope
14xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
15xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
17                             "<soap:Body>"
18                             "<Greet xmlns=\"http://tempuri.org/\">"
19                             "<deviceToken>some device token</deviceToken>"
20                             "<userName>azamsharp</userName>"
21                             "</Greet>"
22                             "</soap:Body>"
23                             "</soap:Envelope>"];
24     
25    NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]];
26     
27    [request addRequestHeader:@"Content-Length" value:messageLength];
28     
29    [request appendPostData:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
30     
31    [request setDelegate:self];
32    [request startAsynchronous];
33 
34     
35}


A good way to find out what header values are required is to use browser or a .NET client to invoke the service and then view the contents of the request header. The result is shown below:

1<?xml
2 version="1.0" encoding="utf-8"?><soap:Envelope
5xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GreetResponse
6 xmlns="http://tempuri.org/"><GreetResult>device
7token:azamsharp</GreetResult></GreetResponse></soap:Body></soap:Envelope>


The code above shows the response returned from the web method "Greet". As you can see the response is quite big and hard to parse. You can specify what kind of response you are interested in and the web service will adhere to it. The following implementation asks for the JSON response, although it returns XML response but the response is greatly reduced.

01-(IBAction)submitButtonClicked:(id)sender
02{
03   
04     
05    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/NotificationService.asmx/Greet"];
06    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
07    [request setRequestMethod:@"POST"];
08    [request addRequestHeader:@"Content-Type" value:@"application/json"];
09    NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]];
10     
11    [request setPostValue:@"device token" forKey:@"deviceToken"];
12    [request setPostValue:@"azamsharp" forKey:@"userName"];
13     
14    [request setDelegate:self];
15    [request startAsynchronous];
16}


In the next section we are going to create a generic handler will will return pure JSON response.

Creating Generic Handler:

Our simple generic handler will return plain JSON. Here is the implementation of the generic handler.

01public class HighHandler : System.Web.IHttpHandler
02    {
03         
04        public virtual bool IsReusable
05        {
06            get
07            {
08                return false;
09            }
10        }
11         
12        public virtual void ProcessRequest(HttpContext context)
13        {
14        var zombie = new Zombie() {Name = "John Doe"};
15            var json = new JavaScriptSerializer();
16 
17 
18            context.Response.Write(json.Serialize(zombie));
19        }
20    }


The handler is available on HighOnCoding at the following URL:

http://highoncoding.com/HighHandler.ashx

The HighHandler.ashx returns the following result:

1{"Name":"John Doe"}


Since, it is returning JSON format we can easily consume it using iOS application as shown below:

01-(IBAction)submitButtonClicked:(id)sender
02{
03   
04    NSURL *url = [NSURL URLWithString:@"http://www.highoncoding.com/highhandler.ashx"];
05    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
06    [request setRequestMethod:@"GET"];
07    [request addRequestHeader:@"Content-Type" value:@"application/json"];
08    
09    NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]];
10     
11      [request setDelegate:self];
12    [request startAsynchronous];
13 
14     
15}
16 
17- (void)requestFinished:(ASIHTTPRequest *)request
18{
19    NSLog(@"status code %d",request.responseStatusCode);
20     
21    if(request.responseStatusCode == 200)
22    {
23        NSLog(@"success");
24        NSString *responseString = [request responseString];
25        NSDictionary *dict = [responseString JSONValue];
26         
27         
28        NSLog(@"%@",[dict valueForKey:@"Name"]);
29    }
30     
31    NSLog(@"request finished");
32}


The above code will display "John Doe" in the console. In the next section we will return a list of objects from the web service which will be consumed by the iOS application.

Consuming List of JSON Objects:

In this section we are going to return a list of objects from the web service instead of a single object. The list of objects will be returned in the JSON format. The ASHX HttpHandler is implemented below:

01 public void ProcessRequest(HttpContext context)
02        {
03            var zombies = new List<Zombie>()
04                              {
05                                  new Zombie() { Name = "John Doe",NoOfKills = 5},
06                                  new Zombie() { Name = "Mary Kate", NoOfKills = 10},
07                                  new Zombie() { Name = "Alex Lowe", NoOfKills = 2}
08                              };
09 
10            var zombie = new Zombie() {Name = "John Doe"};
11            var json = new JavaScriptSerializer();
12 
13 
14            context.Response.Write(json.Serialize(zombies));
15        }


In the above code we just created a list of zombie objects and then returned them in the JSON string format using the JavaScriptSerializer class. If you visit the URL you will get the following result:

1[{"Name":"John Doe","NoOfKills":5},{"Name":"Mary Kate","NoOfKills":10},{"Name":"Alex Lowe","NoOfKills":2}]


Now, we need to consume this JSON string from inside our iOS application and populate a UITableView will the JSON object. The following code initiates a GET request which returns the JSON string representing Zombie objects.  

01-(IBAction)submitButtonClicked:(id)sender
02{
03    NSURL *url = [NSURL URLWithString:@"http://www.highoncoding.com/highhandler.ashx"];
04    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
05    [request setRequestMethod:@"GET"];
06    [request addRequestHeader:@"Content-Type" value:@"application/json"];    
07    NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]];
08  
09    [request setDelegate:self];
10    [request startAsynchronous];    
11}


The requestFinished is fired when the response is returned. If the response code is 200 then we proceed to extract the JSON object from the JSON string and add it to the NSMutableArray called "zombies".

01- (void)requestFinished:(ASIHTTPRequest *)request
02{
03    NSLog(@"status code %d",request.responseStatusCode);
04     
05    if(request.responseStatusCode == 200)
06    {
07        NSLog(@"success");
08        NSString *responseString = [request responseString];
09        NSArray *list = [responseString JSONValue];
10         
11        // iterate through the dict and populate the model
12         
13       for(NSDictionary *item in list)
14       {
15           Zombie *zombie = [[Zombie alloc] init];
16           zombie.name = [item valueForKey:@"Name"];
17            
18           [self.zombies addObject:zombie];
19       }
20         
21                 
22    }
23     
24    [zombieTableView reloadData];
25    [zombieTableView setNeedsDisplay];
26     
27    NSLog(@"request finished");
28}


The output is shown below:



If you like to add more content to each UITableCell then you can use the content view portion of the UITableCell.

Conclusion:

In this article we learned how to communicate with the SOAP web service as well as how to consume JSON using JSON Framework library. We hope this article helps you when you are creating interoperability apps between iOS and the .NET framework.