Search code examples
iphoneiosuibarbuttonitemuibarbuttonitemstyle

refresh the table in view controller by using refresh bar button


I want to add a refresh bar button in my view controller I put in the viewdidload() this code:

UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshTable)];
self.navigationItem.leftBarButtonItem = refreshButton;

and the refreshtable function is :

- (void) refreshTable
{
    [self.tableView reloadData];

    NSLog(@"table is refreshing ....");
}

this is a screenshot of the refresh button: enter image description here

but it doesn't work, shall i add something else in the refreshtable function?, the table view doesn't refreshed!, the message "table is refreshing ...." appears everytime i click on the refresh button, but the table doesn't load new data!

when refreshing, can I have this icon somewhere? enter image description here

If I had two table view in my view controller, and I want when I click on the refresh button, just the first table to be reloaded,

enter image description here

I put the same you code that you suggested, but it doesn't work here! should I do something else?


Solution

  • The issue is you added the data fetching logic in your viewDidLoad (according to your comments).

    The viewDidLoad method will be called when the view is loading. It' won't be called unless you dismiss the view and present it again(it won't be calles if you call the reloadData it's just for reloading the UITableView).

    When you call the reloadData the data source is still with old data, it is not updated.

    So implement your refreshTable method like:

    - (void) refreshTable
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://....../fastnews.php"]];
             [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        });
    }
    
    -(void)fetchedData:(NSData *)responseData
    {
       NSError *error;
       NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
      fastResults = [json objectForKey:@"nodes"];
      [self.tableView reloadData];
    }