I have two UITableViewControllers
A and B, and this is what I'm trying to do when I click on a table view cell in A:
- Prepare to segue from A to B by setting some of B's variables from A.
- Perform segue from A to B.
- B appears.
- Display a "Loading" activity indicator with
[MBProgressHUD][1]
. - In a background task, retrieve data from a URL.
- If an error occurs in the URL request (either no data received or non-200 status code), (a) hide activity indicator, then (b) display UIAlertView with an error message
- Else, (a) Reload B's
tableView
with the retrieved data, then (b) Hide activity indicator
However, this is what's happening, and I don't know how to fix it:
- After clicking a cell in A, B slides in from the right with an empty plain
UITableView
. TheMBProgressHUD
DOES NOT SHOW. - After a while, the
tableView
reloads with the retrieved data, with theMBProgressHUD
appearing very briefly. - The
MBProgressHUD
immediately disappears.
There doesn't seem to be an error with the way the background task is performed. My problem is, how do I display the MBProgressHUD
activity indicator as soon as my B view controller appears? (And actually, how come it's not showing?) Code is below.
A
's prepareForSegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
B *b = (B *)[segue destinationViewController];
// Set some of B's variables here...
}
Relevant methods in B
- (void)viewDidAppear:(BOOL)animated {
[self startOver];
}
- (void)startOver {
[self displayLoadingAndDisableTableViewInteractions];
[self retrieveListings];
[self.tableView reloadData];
[self hideLoadingAndEnableTableViewInteractions];
}
- (void)displayLoadingAndDisableTableViewInteractions {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = @"Loading";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.tableView.userInteractionEnabled = NO;
}
- (void)hideLoadingAndEnableTableViewInteractions {
[MBProgressHUD hideHUDForView:self.view animated:YES];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.tableView.userInteractionEnabled = YES;
}
- (void)retrieveListings {
__block NSArray *newSearchResults;
// Perform synchronous URL request in another thread.
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
newSearchResults = [self fetchNewSearchResults];
});
// If nil was returned, there must have been some error--display a UIAlertView.
if (newSearchResults == nil) {
[[[UIAlertView alloc] initWithTitle:@"Oops!" message:@"An unknown error occurred. Try again later?" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
} else {
// Add the retrieved data to this UITableView's model. Then,
[self.tableView reloadData];
}
}
- (NSArray *)fetchNewSearchResults {
// Assemble NSMutableArray called newSearchResults from NSURLConnection data.
// Return nil if an error or a non-200 response code occurred.
return newSearchResults;
}