我正在试图弄清楚如何使用AFNetworking 2.0。我正在尝试使用用户名和密码发布登录信息。
这是我目前的尝试,但由于没有发送,因此无法正常工作。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"loginName": @"password"};
[manager POST:@"http://xxxx.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
NSLog(@"Data saved");
MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
mainView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController: mainView animated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
NSString *error_msg = (NSString *) error;
[self alertStatus:error_msg :@"Sign in Failed!" :0];
}];
}
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Sign in Failed." :@"Error!" :0];
}
然而,没有任何事情发生,只要继续打印出来:
2014-04-16 20:14:09.903 Slidedrawer[9279:60b] Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e78bd0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
响应将采用JSON格式。任何人都知道我需要在代码中编辑什么或如何解决它?
JSON: {
"_id" = 533cb1c453769a02008c2d55;
name = dddd;
picture = "/img/users/default.jpg";
}
如何访问上面返回的JSON,尝试将每个返回的属性拆分为字符串或整数等...
答案 0 :(得分:1)
试试这个:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"userName": username, @"password": password};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:@"http://asd.com/login.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
要解析回复,请使用responseObject
作为NSDictionary
:
NSString *userName = [responseObject objectForKey:@"userName"];
NSString *password = [responseObject objectForKey:@"password"];
希望这会有所帮助.. :)
答案 1 :(得分:1)
您可以找到答案的Send Nested JSON using AFNetworking。
错误Error Domain = NSCocoaErrorDomain Code = 3840从服务器收到无效的JSON对象。这可能是由于服务器处理您丢失的参数不当造成的。您的参数字典只有一个密钥对象loginName。