2016-01-18 52 views
0

我在这里制作简单的应用程序XCODE 7.1。我只是在tableview cell中显示2个标签和1个图像。我从这个URL解析数据。我只是加载TableviewHere i的数据把代码的ViewController.m文件从JSON解析的数据不加载某些TableView单元格

@interface ViewController() 

@end 

@implementation ViewController 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    activityIndicator.alpha = 1.0; 
    [self.view addSubview:activityIndicator]; 
    activityIndicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2); 
    [activityIndicator startAnimating];//to start animating 
    // Do any additional setup after loading the view, typically from a nib. 


    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 


    NSURL *URL = [NSURL URLWithString:@"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
     if (error) { 
      NSLog(@"Error: %@", error); 
     } else { 
      [activityIndicator stopAnimating]; 
      _responsedic = (NSDictionary*) responseObject; 
      _Worldpopulation = [_responsedic valueForKey:@"worldpopulation"]; 
      _imageURL = [_Worldpopulation valueForKey:@"flag"]; 
      _country = [_Worldpopulation valueForKey:@"country"]; 
      _population = [_Worldpopulation valueForKey:@"population"]; 
      NSLog(@"Data:%@",_imageURL); 
      NSLog(@"Population",_population); 
      NSLog(@"Country",_country); 
      // NSLog(@"%@",_MovieList); 
      //NSLog(@"Array: %@",_imageURL); 
      //NSLog(@"%@",responseObject); 
     } 
    }]; 
    [dataTask resume]; 

} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return 10; 
} 
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    NSString *Identifier = @"mycell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier]; 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier]; 
    // Set and load the images 
    [cell.imageView sd_setImageWithURL:[_imageURL objectAtIndex:indexPath.row] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 

     // Get rid of the activity indicator when the image has been loaded 
    }]; 




    cell.textLabel.text = [_country objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.text = [_population objectAtIndex:indexPath.row]; 
    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    //NSString *rowValue = self.friends[indexPath.row+1]; 
    NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",[_country objectAtIndex:indexPath.row]]; 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"YOU SELECT" 
                message:message 
                delegate:self 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
    [alert show]; 
} 

我使用AFNetworking 3.0和SDWebImage用于图像loading.Data成功解析和与tableview.I显示附下面

截图

Simulator screenshot

是什么问题,所有的数据都没有在的tableview细胞我也把警报对话框上加载成功,但在细胞不显示的tableview数据的每一个单元格中显示。我到处搜索我无法找到解决方案,为此我使用3G连接,因此网速不是问题请别人帮忙。

+1

后,您开始在单元格中的一个非常动荡的状态的异步操作,再加上,出列细胞使之更加复杂。我以前在SDWebImage中遇到过这样的问题,我不得不在UITableViewCell的子类中移动加载图像(仍然使用SDWebImage),以更好地处理'prepareForReuse'情况等等。你需要取消以前的操作,以防你的单元格出列...... –

+0

是的,但我怎样才能加载** UITableView的**单元格子类的图像。 – viratpuar

回答

1

尝试使用完成块中的更新数据重新加载表视图。

NSURL *URL = [NSURL URLWithString:@"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
    if (error) { 
     NSLog(@"Error: %@", error); 
    } else { 
     [activityIndicator stopAnimating]; 
     _responsedic = (NSDictionary*) responseObject; 
     _Worldpopulation = [_responsedic valueForKey:@"worldpopulation"]; 
     _imageURL = [_Worldpopulation valueForKey:@"flag"]; 
     _country = [_Worldpopulation valueForKey:@"country"]; 
     _population = [_Worldpopulation valueForKey:@"population"]; 
     NSLog(@"Data:%@",_imageURL); 
     NSLog(@"Population",_population); 
     NSLog(@"Country",_country); 
     // NSLog(@"%@",_MovieList); 
     //NSLog(@"Array: %@",_imageURL); 
     //NSLog(@"%@",responseObject); 


     //Added Code -> Reloading data on Main queue for update 
     dispatch_async(dispatch_get_main_queue(), ^{ 

      [self.tableview reloadData]; 
     }); 
    } 
}]; 
[dataTask resume]; 

希望,它会帮助你。
谢谢。

+0

仍然没有工作。 – viratpuar

1

enter image description here
1)解析数据和获取数据relaod表

-(void)ParseData 
    { 


      NSURLSession * session = [NSURLSession sharedSession]; 

      NSURL * url = [NSURL URLWithString: @"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"]; 

      //Create URLReques 
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                    cachePolicy:NSURLRequestUseProtocolCachePolicy 
                   timeoutInterval:60.0]; 



      [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 



      // Set Method POST/GET 
      [request setHTTPMethod:@"GET"]; 


      // Asynchronously Api is hit here 

      NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 


       if (!error) //If error nil 
       { 
        //Serialization data 
        NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

        NSLog(@"json %@",json); 

        array=[json valueForKey:@"worldpopulation"]; 


       dispatch_async(dispatch_get_main_queue(), ^(void) { 
        if(array.count!=0) 
        { 

         //Reload table View 
         [_tblView reloadData]; 
        } 
       }); 

       } 
       else 
       { 
        //failure; 
       } 

      }]; 


      [dataTask resume] ; // Executed task 

    } 


2) Table View DataSource 



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 

     if(array.count!=0) 
     { 
      return [array count]; 
     } 
     return 0; 
    } 


    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

     static NSString *CellIdentifier = @"Cell"; 
     UITableViewCell *cell; 
     //= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     cell.backgroundColor =[UIColor whiteColor]; 



     cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

     UILabel *lblCountry=(UILabel*)[cell viewWithTag:2]; 
     lblCountry.text= [[array objectAtIndex:indexPath.row]valueForKey:@"country"]; 

     UILabel *lblPopulation=(UILabel*)[cell viewWithTag:3]; 
     lblPopulation.text= [[array objectAtIndex:indexPath.row]valueForKey:@"population"]; 

     UIImageView *img = (UIImageView *)[cell viewWithTag:1]; 


     [img setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row]valueForKey:@"flag"]]]; 

     return cell; 
    }