Consuming a .NET Web Service from iPhone

This was something which take me a whole (working) day to implement, and I’d like to share the new-found knowledge with everybody interested. We’ll use SOAP with a simple .asmx web service (for the sake of simplicity). I’ll only focus on setting up the connection, so tasks such as authentication and security are to be implemented by you.

First, we’ll need the service. Our simple little web service will return void, and take two parameters, a user name and an integer value representing the user’s score (yes it’s a high score table). The service will take care of putting these values into a database. The SQL table looks like this:

ID Primary key, Identity seed (1,1)
Name nvarchar(50)
Score Int

 

The code of the service (assuming you’ve created a ConnectionString called myString in the web.config, and included System.Web.Configuration and System.Data.SqlClient in your class:

[WebMethod]
public void postScore(string name, string score)
{
string connStr = WebConfigurationManager.ConnectionStrings[“myString”].ConnectionString;
SqlConnection theConnection = new SqlConnection(connStr);
String commandText = “INSERT INTO iPhone (Name, Score) VALUES (@Name, @Score)”;
SqlCommand theCommand = new SqlCommand              (commandText, theConnection);
theCommand.Parameters.AddWithValue(“Name”, name);
theCommand.Parameters.AddWithValue(“Score”, score);
using (theConnection)
{
  theConnection.Open();
  theCommand.ExecuteNonQuery;
}

That was all you on the server side. Now publish your service on the Internet, (I’ll assume you’ve published it on http://testService.com, with an asmx file called theService. Now open http://testService.com/theService.asmx in the browser, and select the postScore operation. All information you’ll need to set up your request for the service will be written there.

I wouldn’t like to repeat myself, so I won’t post the setup information here, it’ll be written on the iPhone client. So let’s head towards it and write it quickly.

Now fire up xCode, and let’s write the client which consumes the service. It will look like this:

-(IBAction)publishScoreButtonPressed
{
NSString* soapMessage = [NSString stringWithFormat:
    @”<?xml version=\”1.0\” encoding=\”utf-8\”?>
    <soap:Envelope xmlns:xsi=”\http://w3.org/2001/XMLSchema-instance\
    xmlns:xsd=\”http://w3.org/2001/XMLSchema\
    xmlns:soap=\”http://schemas.xmlsoap.org/envelope/\”>
    <soap:Body>
    <postScore xmlns=\”http://tempuri.org\”>
    <score>%d</score>
    <name>%@</name>
    </postScore>
    </soap:Body>
    </soap:Envelope>”, scoreInt, nameString];
NSURL* theUrl = [NSURL URLWithString:@http://testService.com/theService.asmx”];
NSString* msgLength = [NSString stringWithFormat:@”%d”, [soapMessage length]];
NSMutableRequest* theRequest = [NSMutableRequest requestWithURL:theUrl];
[theRequest addValue:@”text/xml; charset=utf-8” forHTTPHeaderField:@”Content-Type”];
[theRequest addValue:@”http://tempuri.org/postScore” forHTTPHeaderField:@”SOAPAction”];
[theRequest setHTTPMethod:@”POST”];
[theRequest addValue:msgLength forHTTPHeaderField:@”Content-Length”];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self];
}

As soon as initWithRequest is called, the request will be sent to the given server (in an asynchronous manner). To see what comes back as the result, implement the following method:

-(void)connection: (NSURLConnection*) connection didReceiveData: (NSData*)data
{
}

Examine the value stored in data (encode it to a string and log it) to see the result of your request.

Consuming a .NET web service from an iPhone is relatively easy, as you’ve seen. Feel free to experiment (I’d say DO experiment) to gain a deeper understanding of the players.

Advertisements

Tags: , ,

4 responses to “Consuming a .NET Web Service from iPhone”

  1. Damodar says :

    Hello Gergely Koncz,

    Great work. I have been writing .Net webservice for some of my iphone apps..

    For consuming .Net webservice in ihpoe i write one more intermediate layer again .net which communicates between iphone code and wcf webservice.

    Kindly let me know if we can avoid that intermediate layer . If you have source code kindly send me to my id damodar.puttur@gmail.com

    Thanks in advance.

    Regards,
    -Dam

  2. Wasim says :

    nice post. It helped me a lot to understand what exactly the way to access the .Net web services. I have experience with php services but wandering to work with .Net ones too. Thanks for a start.

  3. PGC says :

    Can you please send me the sample code for this example to my email id [pro_indigo@live.com]. I am just a beginner in terms of iPhone programming. It’s hardly been two weeks since I have been learning the subject. Some kind of sample code or tutorial would be of tremendous help to me.

    Thanks.

  4. Rodrigo says :

    Hi. Nice post, everything works fine. But I have a question. In your code, the URLWithString parameter is hardcoded, ok? Supose you change your URL for whatever reason, you must recompile your application with the new parameter. So, what is the best practice regarding this situation? Put it in the app plist, or what? Thanks!

Leave a Reply

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: