400 HTTP响应时,在Alert View上显示API Response JSON格式的错误结果

时间:2014-05-14 17:08:07

标签: ios json

希望像在图片中看到的那样实现这一目标

enter image description here

以下信息正常,但我想要做的是向用户显示来自API的响应,因为即使我验证以下字段,nick,pass_field,type_account,email。 API会响应该用户名是否正在使用或电子邮件是否无效。你可以在下面看到。我想要做的是修改此代码并使其响应每个字段的API响应向用户发出警报,JSON仅在400 HTTP响应期间响应以下字段

{“nick”:[“需要用户名”]}

{“nick”:[“用户名eddwinpaz正在使用中”]}

{“email”:[“需要电子邮件字段”]}

{“email”:[“输入有效的电子邮件”]}

{“pass_field”:[“需要传递字段”]}

以下是我的回复

2014-05-14 12:30:09.944 mobile-app[2337:60b] PostData: nick=&pass_field=&email=&type_account=0
2014-05-14 12:30:30.998 mobile-app[2337:60b] Response code: 400
2014-05-14 12:30:30.998 mobile-app[2337:60b] Response ==> {"nick": ["Username eddwinpaz is in use"]}

这是我的ViewController.m

- (IBAction)registerClicked:(id)sender {
NSInteger success = 0;
@try {

        NSString *post =[[NSString alloc] initWithFormat:@"nick=%@&pass_field=%@&email=%@&type_account=%ld",[self.txtUsername text],
                         [self.txtPassword text],
                         [self.txtEmail text],
                         (long)[self.userType selectedSegmentIndex]];
        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"http://api.samplewebsite.ca/user-register/?format=json"];

        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %ld", (long)[response statusCode]);

        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        NSLog(@"Response ==> %@", responseData);

        if ([response statusCode] == 201)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            NSError *error = nil;
            NSDictionary *jsonData = [NSJSONSerialization
                                      JSONObjectWithData:urlData
                                      options:NSJSONReadingMutableContainers
                                      error:&error];

            success = [jsonData[@"success"] integerValue];
            NSLog(@"Success: %ld",(long)success);


                NSLog(@"Login SUCCESS");

                NSString *error_msg = (NSString *) jsonData[@"error_message"];

                [self alertStatus:error_msg :@"Your Account has been created, Now login" :0];
                [self performSegueWithIdentifier:@"login" sender:self];



        } else {

            [self alertStatus:@"Connection Failed" :@"Registration Failed, Please check empty or invalid fields!" :0];
        }

}
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }

}

1 个答案:

答案 0 :(得分:0)

这比使用AlertView好多了。要执行此操作,请在字段上方添加三个带有右对齐的标签(emailErrorLabel,nickErrorLabel,passErrorLabel)。

responseData转换为NSDictionary,以便您可以提取密钥。然后你会得到以下内容:

if ([response statusCode] == 201)
{ ... }
else if ([response statusCode] == 400)
{ 
   NSArray *keys = [responseData allKeys];
   for (NSString * key in keys)
   {
     if ([key isEqualToString:@"email"])
       emailErrorLabel.text = [responseData objectForKey:key];
     else if ([key isEqualToString:@"nick"])
       nickErrorLabel.text = [responseData objectForKey:key];
     else if ([key isEqualToString:@"pass_field"])
       passErrorLabel.text = [responseData objectForKey:key];
   }

}