2016-01-18 55 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; 
    }