我为用户名创建了一个文本字段,为密码和按钮创建了另一个文本字段。现在在JSON帖子中,如果我输入了错误的详细信息,则必须为我显示错误消息。如果我输入了正确的细节,它应该转到另一个视图控制器。 怎么做?
self.urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
self.serviceURLReq = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://dokitatesting.com/API/doctorLogin"]];
self.serviceURLReq.HTTPMethod = @"POST";
[self.serviceURLReq setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSString * dataToServer = [NSString stringWithFormat:@"UserName=%@&Password=%@",self.userNameField.text,self.passwordField.text];
NSData *postData = [dataToServer dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
[self.serviceURLReq setValue:postLength forHTTPHeaderField:@"Content-Length"];
[self.serviceURLReq setHTTPBody:postData];
if ([self.userNameField hasText] && [self.passwordField hasText]) {
self.dataTask = [self.urlSession dataTaskWithRequest:self.serviceURLReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//1
AD.serverResponseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"server response is %@",AD.serverResponseDict);
dispatch_async(dispatch_get_main_queue(), ^{ // 2
LVC = [self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
[self.navigationController pushViewController:LVC animated:YES]; // 3
});
});
}];
[self.dataTask resume];
}
这是我编写的代码,当我输入错误的详细信息时,它只是显示服务器响应的消息是(null)
答案 0 :(得分:1)
你必须知道你何时获得这些错误,所以在登录调用中有一个完成处理程序会很好。之后,您可以通过JSON错误指定是否显示错误,或导航到另一个视图控制器。以下是在Objective-C中显示错误的方法:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
这就是你导航到另一个视图控制器的方式:
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];