2012-11-26 76 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   
    } 
} 

希望這有助於別人