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:
1 | public class NotificationService : System.Web.Services.WebService |
4 | public string HelloWorld() |
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 |
05 | ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; |
06 | [request setRequestMethod:@"POST"]; |
07 | [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"]; |
09 | [request setDelegate:self]; |
10 | [request startAsynchronous]; |
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 |
03 | NSLog(@"status code %d",request.responseStatusCode); |
05 | if(request.responseStatusCode == 200) |
08 | NSString *responseString = [request responseString]; |
09 | NSLog(@"%@",responseString); |
12 | NSLog(@"request finished"); |
15 | - (void)requestFailed:(ASIHTTPRequest *)request |
17 | NSError *error = [request error]; |
18 | NSLog(@"%@",error.localizedDescription); |
When you run the iOS application you will get the following in your console.
1 | <?xml version="1.0" encoding="utf-8"?> |
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:
2 | public string Greet(string deviceToken,string userName) |
4 | return deviceToken + ":" + userName; |
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 |
04 | ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; |
05 | [request setRequestMethod:@"POST"]; |
06 | [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"]; |
10 | NSString *soapMessage = [NSString stringWithFormat: |
11 | @"<?xml version=\"1.0\" encoding=\"utf-8\"?>" |
19 | "<deviceToken>some device token</deviceToken>" |
20 | "<userName>azamsharp</userName>" |
25 | NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]]; |
27 | [request addRequestHeader:@"Content-Length" value:messageLength]; |
29 | [request appendPostData:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; |
31 | [request setDelegate:self]; |
32 | [request startAsynchronous]; |
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:
2 | version="1.0" encoding="utf-8"?><soap:Envelope |
7 | token: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 |
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]]; |
11 | [request setPostValue:@"device token" forKey:@"deviceToken"]; |
12 | [request setPostValue:@"azamsharp" forKey:@"userName"]; |
14 | [request setDelegate:self]; |
15 | [request startAsynchronous]; |
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.
01 | public class HighHandler : System.Web.IHttpHandler |
04 | public virtual bool IsReusable |
12 | public virtual void ProcessRequest(HttpContext context) |
14 | var zombie = new Zombie() {Name = "John Doe"}; |
15 | var json = new JavaScriptSerializer(); |
18 | context.Response.Write(json.Serialize(zombie)); |
The handler is available on HighOnCoding at the following URL:
http://highoncoding.com/HighHandler.ashx
The HighHandler.ashx returns the following result:
Since, it is returning JSON format we can easily consume it using iOS application as shown below:
01 | -(IBAction)submitButtonClicked:(id)sender |
05 | ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; |
06 | [request setRequestMethod:@"GET"]; |
07 | [request addRequestHeader:@"Content-Type" value:@"application/json"]; |
09 | NSString *messageLength = [NSString stringWithFormat:@"%d",[soapMessage length]]; |
11 | [request setDelegate:self]; |
12 | [request startAsynchronous]; |
17 | - (void)requestFinished:(ASIHTTPRequest *)request |
19 | NSLog(@"status code %d",request.responseStatusCode); |
21 | if(request.responseStatusCode == 200) |
24 | NSString *responseString = [request responseString]; |
25 | NSDictionary *dict = [responseString JSONValue]; |
28 | NSLog(@"%@",[dict valueForKey:@"Name"]); |
31 | NSLog(@"request finished"); |
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) |
03 | var zombies = new List<Zombie>() |
05 | new Zombie() { Name = "John Doe",NoOfKills = 5}, |
06 | new Zombie() { Name = "Mary Kate", NoOfKills = 10}, |
07 | new Zombie() { Name = "Alex Lowe", NoOfKills = 2} |
10 | var zombie = new Zombie() {Name = "John Doe"}; |
11 | var json = new JavaScriptSerializer(); |
14 | context.Response.Write(json.Serialize(zombies)); |
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 |
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]]; |
09 | [request setDelegate:self]; |
10 | [request startAsynchronous]; |
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 |
03 | NSLog(@"status code %d",request.responseStatusCode); |
05 | if(request.responseStatusCode == 200) |
08 | NSString *responseString = [request responseString]; |
09 | NSArray *list = [responseString JSONValue]; |
13 | for(NSDictionary *item in list) |
15 | Zombie *zombie = [[Zombie alloc] init]; |
16 | zombie.name = [item valueForKey:@"Name"]; |
18 | [self.zombies addObject:zombie]; |
24 | [zombieTableView reloadData]; |
25 | [zombieTableView setNeedsDisplay]; |
27 | NSLog(@"request finished"); |
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.