-1

Want to achieve this like you see in the image

enter image description here

The following information below works properly but what i want to do is display to the user the response from the API because even when i validate the following fields, nick, pass_field, type_account , email. The API responds whether that username is in use or if the email is invalid. as you can see below. What i want to do is modify this code and make it response a alert to the user with the API response for each field the JSON only responds the following fields during 400 HTTP Response

{"nick": ["Username required"]}

{"nick": ["Username eddwinpaz is in use"]}

{"email": ["Email field is required"]}

{"email": ["Type a valid email"]}

{"pass_field": ["pass field is required"]}

Here is my response

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"]}

Here is my 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];
    }

}
Eddwin Paz
  • 2,842
  • 4
  • 28
  • 48
  • What problem are you having? The code you posted shows no attempt to do what you are asking. Try first and then update your question with a specific issue if you run into one. – rmaddy May 14 '14 at 17:15
  • I didn't understand a word of it – Gruntcakes May 14 '14 at 17:19
  • i want to show the JSON that comes as a result on alerts and not from iOS validation because the API validates if nick field exists alredy on database. – Eddwin Paz May 14 '14 at 17:31
  • I put an answer that is along the lines of what you're looking for, but please reconsider not using an alert for this. – LyricalPanda May 14 '14 at 17:40
  • @LyricalPanda updated the question and added an image – Eddwin Paz May 14 '14 at 17:52
  • @eddwinpaz I've updated my answer to reflect the changes. Thank you for being so open to switching from a `UIAlertView` – LyricalPanda May 14 '14 at 17:59

1 Answers1

0

This looks a lot better than using an AlertView. To do this, add three labels with Right Justification above the fields (emailErrorLabel, nickErrorLabel, passErrorLabel).

Convert responseData into an NSDictionary so you can extract the keys. Then you'll have something like the following:

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];
   }

}
LyricalPanda
  • 1,424
  • 14
  • 25
  • this is REgisterViewController.h http://imageshack.com/a/img838/1282/rzeq.png and this is .m http://imageshack.com/a/img845/2524/ehw8.png – Eddwin Paz May 14 '14 at 18:19
  • Check this link out. ResponseData really shouldn't be a string when it's in that format. Change it to an `NSDictionary` based on the return you specified in your question http://stackoverflow.com/questions/12603047/how-to-convert-nsdata-to-nsdictionary – LyricalPanda May 15 '14 at 05:46