2012-11-26 55 views
1

我有一个.aspx文件与一些webMethods的内部。我想从iOS(iPhone)应用程序中使用这些方法。 将WebMethod代码如下:呼叫ASP.NET的WebMethod解析

[WebMethod] 
public static string Login(string username, string password) 
{ 
    return username + ":" + password; 
} 

为了测试这个的WebMethod我用:

$.ajax({ 
    type: "POST", 
    url: "DataProvider.aspx/Login", 
    data: JSON.stringify({ username: "myUserName", password: "myPassword" }), 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (result) { alert(result.d); }, 
    error: function (xhr, ajaxOptions, thrownError) { 
     alert(xhr.status); 
     alert(thrownError); 
    } 
}); 

所以一切正常,我也得到"myUserName:myPassword"回来,现在我想从里面的Xcode 4.5做同样的。2,所以我创建了一个新的iPhone应用程序,并把里面的ViewController一个label(lbResult)和button(btDoLogin)和分配出口和行动。

请注意,我不感兴趣,异步或代表,我只想把数据传回,并能够分析它(JSON)。

对不起,这么具体的相关细节,但我看到了很多类似的问题,并没有一个答案为我工作。对于我读的这是我的理解,这可以使用NSURLConnection解决。例如,这个问题Passing parameters to a JSON web service in Objective C与我需要的非常相似,但是我得到的是整个页面! (意思是它的下载整个页面,而不是调用Web方法)另外,我需要通过2个参数,问题只使用1(我不知道如何将它们在连接字符串分隔)。

现在,究竟是什么,我需要走出IBAction为内连接到这个特殊的webmethod,并得到返回值?

- (IBAction)btDoLogin:(id)sender { 
    // magic code goes here! 
} 

Thanks.-

回答

4

事实证明,问题是how to pass the parameters in a JSON format,而不是一个正常的连接字符串。下面是完整的代码:

- (IBAction)btSend:(id)sender { 
    NSError *errorReturned = nil; 
    NSString *urlString = @"http://192.168.1.180:8080/DataProvider.aspx/DoLogin"; 
    NSURL *url = [NSURL URLWithString:urlString]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod: @"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
    [dict setObject:@"myUsername" forKey:@"username"]; 
    [dict setObject:@"myPassword" forKey:@"password"]; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions  error:&errorReturned]; 
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody: jsonData]; 

    NSURLResponse *theResponse =[[NSURLResponse alloc]init]; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned]; 
    if (errorReturned) 
    { 
     //...handle the error 
    } 
    else 
    { 
     NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@", retVal); 
     //...do something with the returned value   
    } 
} 

希望这有助于别人