RequestResponse我没有收到

时间:2015-02-28 07:16:38

标签: ios json iphone nsurlrequest

我想用api传递这些数据。我想获得countryname id,代码,但我没有得到怎么做。

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

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用AFNetworking?它会让你的生活更轻松。

从这里下载代码AFNetworking 并将AFNetworking文件夹导入您的项目。

您可以使用以下代码获取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);
}];