2016-05-22 2 views
0

этот вопрос был упомянут много раз здесь, но мой случай немного отличается от того, что я делаю, поскольку в UITabBarController есть два UITableViewController, когда я переключаюсь на второй UITableViewController, метод cellForRowAtIndextPath не запускается для заполнения UITableViewController с данными, которые тянут с моим сервера, используя AFNetworking после поиска для многого решения по Интернету всех вопросов, которые я нашел не включает UITabBarController такого, как question 1, question 2, question 3, question 4, question 5,cellForRowAtIndexPath не вызванный внутри UITabBarController

ее е код, который я пытаюсь использовать:

#import "newsAndEventTableViewController.h" 
#import "SplashViewController.h" 
#import "sharedVariables.h" 
#import"AFNetworking.h" 
#import "UIWebView+AFNetworking.h" 
#import "SDWebImageCompat.h" 
#import "SDWebImageDownloaderOperation.h" 
#import "SDWebImageDownloader.h" 
#import "MyGeeksTableViewController.h" 
#import "geeksEvent.h" 




    @interface newsAndEventTableViewController() 
    { 
    NSMutableArray *events; 
    geeksEvent *eventObject; 
    NSMutableArray *listOfEventsObjects; 
    } 
    @end 

@implementation newsAndEventTableViewController 



- (void)viewDidLoad { 
     [super viewDidLoad]; 
     self.tableView.delegate = self; 

    UIImage *image = [UIImage imageNamed:@"image.png"]; 
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image]; 


} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

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



    return [events count]; 
} 




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



{ 

     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 

     [manager GET:@"http://myserver.com/get.php" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { 
      //  NSArray *products = [jsonDict objectForKey:@"images"]; 
      //  [products enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop){ 
      //   // NSString *productIconUrl = [obj objectForKey:@"imageUrl"]; 
      // 
      //   }]; 
      // 


      NSLog(@"the response is: %@",responseObject); 

      events = [responseObject objectForKey:@"events"]; 



      for (int i = 0; i < [events count];i++) { 


       eventObject = [events objectAtIndex:i]; 



       [listOfEventsObjects addObject:eventObject]; 



      } 













     } 



      failure:^(NSURLSessionTask *operation, NSError *error) { 
       NSLog(@"Error: %@", error); 

       UIAlertController * alert= [UIAlertController 
               alertControllerWithTitle:@"Error" 
               message:@"pls check your internet connection" 
               preferredStyle:UIAlertControllerStyleAlert]; 

       UIAlertAction* yesButton = [UIAlertAction 
              actionWithTitle:@"retry" 
              style:UIAlertActionStyleDefault 
              handler:^(UIAlertAction * action) 
              { 
               //Handel your yes please button action here 


              }]; 
       UIAlertAction* noButton = [UIAlertAction 
              actionWithTitle:@"No, Cancel" 
              style:UIAlertActionStyleDefault 
              handler:^(UIAlertAction * action) 
              { 
               //Handel no, thanks button 

              }]; 

       [alert addAction:yesButton]; 
       [alert addAction:noButton]; 

       [self presentViewController:alert animated:YES completion:nil]; 


      }]; 







    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    // Display recipe in the table cell 
    geeksEvent *event = [events objectAtIndex:indexPath.row]; 


    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100]; 
    recipeImageView.image = [UIImage imageNamed:@"placeholderimage"]; 

    UILabel *eventTitle = (UILabel *)[cell viewWithTag:200]; 
    eventTitle.text = event.eventTitle; 
    NSLog(@"the event title is: %@",event.eventTitle); 

    UILabel *eventDesc = (UILabel *)[cell viewWithTag:300]; 
    eventDesc.text = event.eventShortDiscription; 

    // Assign our own background image for the cell 
    // UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath]; 

    // UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background]; 
    // cellBackgroundView.image = background; 
    // cell.backgroundView = cellBackgroundView; 


    return cell; 
} 

/* 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath]; 

// Configure the cell... 

return cell; 
} 
*/ 

/* 
// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { 
// Return NO if you do not want the specified item to be editable. 
return YES; 
} 
*/ 

/* 
// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
if (editingStyle == UITableViewCellEditingStyleDelete) { 
// Delete the row from the data source 
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
} else if (editingStyle == UITableViewCellEditingStyleInsert) { 
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
} 
} 
*/ 

/* 
// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { 
} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { 
// Return NO if you do not want the item to be re-orderable. 
return YES; 
} 
*/ 

/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
// Get the new view controller using [segue destinationViewController]. 
// Pass the selected object to the new view controller. 
} 
*/ 

@end 
+0

Не могли бы вы сделать NSLog из [числа событий] внутри numberOfRowsInsection –

+0

это дает мне нулю даже в два случае, если я делаю AFHTTPrequest внутри RowForIndexPath или используя viewDidLoad –

+0

, может быть, потому, что ваш запрос возвращает нулевые элементы или я ошибаюсь? –

ответ

1

Код внутри success блока AFNetworking запроса вызывается асинхронно, и поэтому нет никаких данных при отображении tableView.

Как предложение, вы можете переместить AFNetworking запрос вне tableView:cellForRowAtIndexPath: метода (напр .: viewDidLoad), потому что это будет инициирования запроса каждый раз, когда приложение хочет отобразить ячейку, в результате чего приложение не отвечает и потреблять пользователя пропускная способность.

Таким образом, используя приведенные выше предложения, то код будет:

#import "newsAndEventTableViewController.h" 
#import "SplashViewController.h" 
#import "sharedVariables.h" 
#import"AFNetworking.h" 
#import "UIWebView+AFNetworking.h" 
#import "SDWebImageCompat.h" 
#import "SDWebImageDownloaderOperation.h" 
#import "SDWebImageDownloader.h" 
#import "MyGeeksTableViewController.h" 
#import "geeksEvent.h" 




    @interface newsAndEventTableViewController() 
    { 
    NSMutableArray *events; 
    geeksEvent *eventObject; 
    NSMutableArray *listOfEventsObjects; 
    } 
    @end 

@implementation newsAndEventTableViewController 



- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.tableView.delegate = self; 

    UIImage *image = [UIImage imageNamed:@"image.png"]; 
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image]; 


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 

    [manager GET:@"http://myserver.com/get.php" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { 

     NSLog(@"the response is: %@",responseObject); 

     events = [responseObject objectForKey:@"events"]; 

     for (int i = 0; i < [events count];i++) { 
      eventObject = [events objectAtIndex:i]; 

      [listOfEventsObjects addObject:eventObject]; 
     } 

     // Calling reload data after request is done 
     [self.tableView reloadData]; 
     } 

     failure:^(NSURLSessionTask *operation, NSError *error) { 
     NSLog(@"Error: %@", error); 

     UIAlertController * alert= [UIAlertController 
             alertControllerWithTitle:@"Error" 
             message:@"pls check your internet connection" 
             preferredStyle:UIAlertControllerStyleAlert]; 

     UIAlertAction* yesButton = [UIAlertAction 
            actionWithTitle:@"retry" 
            style:UIAlertActionStyleDefault 
            handler:^(UIAlertAction * action) 
            { 
             //Handel your yes please button action here 


            }]; 
     UIAlertAction* noButton = [UIAlertAction 
            actionWithTitle:@"No, Cancel" 
            style:UIAlertActionStyleDefault 
            handler:^(UIAlertAction * action) 
            { 
             //Handel no, thanks button 

            }]; 

     [alert addAction:yesButton]; 
     [alert addAction:noButton]; 

     [self presentViewController:alert animated:YES completion:nil]; 
     }]; 

} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [events count]; 
} 

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

{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    // Display recipe in the table cell 
    geeksEvent *event = [events objectAtIndex:indexPath.row]; 


    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100]; 
    recipeImageView.image = [UIImage imageNamed:@"placeholderimage"]; 

    UILabel *eventTitle = (UILabel *)[cell viewWithTag:200]; 
    eventTitle.text = event.eventTitle; 
    NSLog(@"the event title is: %@",event.eventTitle); 

    UILabel *eventDesc = (UILabel *)[cell viewWithTag:300]; 
    eventDesc.text = event.eventShortDiscription; 

    // Assign our own background image for the cell 
    // UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath]; 

    // UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background]; 
    // cellBackgroundView.image = background; 
    // cell.backgroundView = cellBackgroundView; 


    return cell; 
} 

@end 
+0

, даже я попробую его внутри viewdidload или с помощью viewwillappear samething happend –

+0

Обратите внимание, что я добавил запрос reloadData после запроса кончено. Это вызовет отображение 'tableView' после того, как массив' events' будет обновлен данными из запроса. –

Смежные вопросы