2013-12-20 36 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"); 
} 
相关问题