Search code examples
c#objective-cxmlhttprequestwebmethod

passing parameters to web method


On a web server is the following method:

[WebMethod()]
public static string login(string userName, string password)
{
    if (usernName == "test" && password == "test")
    {
         return "validated";
    }
    return "error";
}

I'm trying to connect to it with the following Objective C code:

NSString *post = [NSString stringWithFormat:@"userName="test"&password="test"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSString *serverURLString = @"http://myURL.aspx/login";
NSURL *serverURL = [NSURL URLWithString:serverURLString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverURL];
[request setHTTPMethod:@"POST"];

[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

NSHTTPURLResponse *urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

NSLog(@"response data = %@", responseData);

I got lost in ignorant newbie land and thought the last line would print out either "validated" or "error" in my Objective C console but it returns an integer (which I'm sure is obvious to those of you who have done this before =)).

Can anyone tell me how I would get to see the webMethod return value in my Objective C log?

-EDIT- I've just noticed that I get an HTTP response status code of 200, regardless of whether I use the correct userName/password combination or not, which I'm guessing could also mean the issue lies elsewhere?


Solution

  • You can create an NSString using the NSData returned in the response. E.g.:

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];