Search code examples
iosjsoniphonensurlrequest

RequestResponse nil I'm getting


I want to pass this data using api. I want to get countryname id,code,but I'm not getting how to do.

-(void) getCountries
{
    NSString *get=[[NSString alloc]initWithFormat:@"city id=%@,&lang=%@",[self.countryCode text],[self.countryList textInputMode]];
    NSLog(@"postDat :%@",get);


    NSURL *url=[NSURL URLWithString:@"http://demo28.know3.com/api/country-list/en.html"];
    NSData*postData=[get 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:@"contentLength"];
    //[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:postData];


    NSError *error=[[NSError alloc]init];
    NSHTTPURLResponse *response=nil;
    NSData *urldata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"Response code %d",(int)[response statusCode]);
    if ([response statusCode]<=200 &&[response statusCode]<=300) {
        NSString *responseData=[[NSString alloc]initWithData:urldata encoding:NSASCIIStringEncoding];
        NSLog(@"Response=%@",responseData);
        NSError *error=nil;NSDictionary *jsondata=[NSJSONSerialization JSONObjectWithData:urldata options:NSJSONReadingMutableContainers error:&error];
        success=[jsondata[@"success"]integerValue];

        NSLog(@"success:%ld",(long)success);
        if (success==0) {
            NSLog(@"Country");
            [self alertStatus:@" country " :@"country  List scucess!"];

        }else {
            NSString *errormsg=(NSString *)jsondata[@"errormesg"];
            [self alertStatus:errormsg :@"  Failed"];
        }
    }else{
        [self alertStatus:@"connection Failed" :@"sign in failed"];
    }
}


-(void)alertStatus:(NSString *)message :(NSString *)title
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];

    [alert show];
}

Solution

  • Have you tried using AFNetworking? It will make your life much more easier.

    Download the code from here AFNetworking And import the AFNetworking folder to your project.

    You can use the following code to get country list in an NSDictionary

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];