5

I have the following on one of my tabs:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.clearsSelectionOnViewWillAppear = YES;

    UIRefreshControl* refreshControl = [[UIRefreshControl alloc] init];
    refreshControl.attributedTitle   = [[NSAttributedString alloc] initWithString:@"Sync"];
    [refreshControl addTarget:self 
                       action:@selector(refresh:) 
             forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;

    //### Workaround: http://stackoverflow.com/a/19126113/1971013
    dispatch_async(dispatch_get_main_queue(), ^
    {
        [self.refreshControl beginRefreshing];
        [self.refreshControl endRefreshing];
    });
}

- (void)refresh:(id)sender
{
    if ([Settings sharedSettings].haveAccount == YES)
    {
        [[DataManager sharedManager] synchronizeWithServer:^(NSError* error)
        {
            [sender endRefreshing];
        }];
    }
    else
    {
        [sender endRefreshing];
    }
}

Refresh control starts spinning normally when pulling down table.

However, when I, while it spins, shown an other tab shortly and then go back, the refresh control stops spinning.

Any idea why?

meaning-matters
  • 21,929
  • 10
  • 82
  • 142

2 Answers2

5

Try moving this piece of code from viewDidLoad to viewWillAppear:

//### Workaround: http://stackoverflow.com/a/19126113/1971013
dispatch_async(dispatch_get_main_queue(), ^
{
    [self.refreshControl beginRefreshing];
    [self.refreshControl endRefreshing];
});
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
  • Marvellous idea! Let me help you get more point than me :-) Thanks! – meaning-matters Mar 25 '14 at 21:33
  • 1
    This is actually wrong. What if the success to the API call wasn't received yet? If you do the tab switch fast enough, you can observe that the refresh control ends refreshing before the success block was called. This leads to misinterpretation for the end user. – GoGreen Apr 09 '15 at 08:16
2

The more sensible approach to fix this issue would be to end / begin refreshing on viewWillDisappear / viewWillAppear respectively

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    refreshControl.endRefreshing()
}

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(animated)

    if isLoadingData {
        // for simplicity using harcoded height for refresh control
        tableView.setContentOffset(CGPoint(x: 0, y: -60), animated: false)
        refreshControl.beginRefreshing()
    }
}
vasantpatel
  • 371
  • 4
  • 8