2013-12-20 94 views
0

我很困惑發送登錄信息到web服務器。我已經部分完成了這個過程,但我無法繼續前進,因爲我無法理解整個過程。如何從ios應用程序向webserver發送登錄信息?

這就是我所做的。

- (IBAction)loginUser:(id)sender { 
NSString *userName = self.userNameTextField.text; 
NSString *password = self.passwordTextField.text; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.16:8080/WebServices/Authentication.php"]]; 

[request setHTTPMethod:@"POST"]; 

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; 
[dictionary setObject:userName forKey:@"pseudo"]; 
[dictionary setObject:password forKey:@"pass"]; 


NSData *data = [dictionary copy]; 


[request setHTTPBody:data]; 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
if(!connection){ 
    NSLog(@"Connection Failed"); 


} 

} 

,當我嘗試把登錄信息後,運行應用程序,我的應用程序崩潰......說。

2013-12-27 20:00:00.177 Authentication[6820:380f] -[__NSDictionaryI length]: unrecognized selector sent to instance 0x8c265e0 
    (lldb) 

回答

0

所以

[dictionary copy] 

返回NSDictionary對象,而不是一個NSData。這就是爲什麼你會得到一個例外。你需要做的是將字典轉換爲NSString(XML或JSON)並從中創建NSData對象。

0

試試這個:

- (IBAction)loginUser:(id)sender { 
    NSString *userName = self.userNameTextField.text; 
    NSString *password = self.passwordTextField.text; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.16:8080/WebServices/Authentication.php"]]; 

    [request setHTTPMethod:@"POST"]; 

    NSString *postParameters = [NSString stringWithFormat:@"pseudo=%@&pass=%@", userName, password]; 

    [request setHTTPBody:[postParameters dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    if(!connection){ 
     NSLog(@"Connection Failed"); 
    } 
} 
0
NSMutableDictionary *dictionary = [NSMutableDictionary new]; 
[dictionary setObject:userName forKey:@"pseudo"]; 
[dictionary setObject:password forKey:@"pass"]; 

NSURL *theUrl = [NSURL URLWithString: @"http://192.168.1.16:8080/WebServices/Authentication.php"]; 

NSMutableURLRequest urlRequest = [NSMutableURLRequest requestWithURL:theUrl]; 
NSError *error; 

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; 
NSString *jsonString; 

if (!jsonData) { 
} else { 
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
} 

[urlRequest setValue: @"application/json" forHTTPHeaderField:@"accept"]; 
[urlRequest setHTTPMethod:@"POST"]; 
[urlRequest setHTTPBody: jsonData]; 
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"content-type"]; 



NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; 
if(!connection){ 
    NSLog(@"Connection Failed"); 
} 
相關問題