Question

I want to show an activity indicator during downloading. But when I click the button which starts the download I see the clicked button until the download has finished. What am I doing wrong?

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  if (buttonIndex == 1) {

    //Update begins
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] init];
    UIView *overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    activityIndicatorView.center = overlayView.center;
    [overlayView addSubview:activityIndicatorView];
    [self.tabBarController.view addSubview:overlayView];
    [activityIndicatorView startAnimating];

    UpdateModel *updateModel = [[UpdateModel alloc] init];
    [updateModel deleteOldDatabase];
    [updateModel downloadNewDatabase];

    //Update done
    [overlayView removeFromSuperview];
    [activityIndicatorView removeFromSuperview];
    [activityIndicatorView stopAnimating];
  }
}
Was it helpful?

Solution

I guess those are blocking process ?

[updateModel deleteOldDatabase];
[updateModel downloadNewDatabase];

I guess the problem is just that you are blocking the UI of your application with your database update. Try doing the work on a background tread like this :

//Update begins
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] init];
    UIView *overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    activityIndicatorView.center = overlayView.center;
    [overlayView addSubview:activityIndicatorView];
    [self.tabBarController.view addSubview:overlayView];
    [activityIndicatorView startAnimating];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UpdateModel *updateModel = [[UpdateModel alloc] init];
        [updateModel deleteOldDatabase];
        [updateModel downloadNewDatabase];

        dispatch_async(dispatch_get_main_queue(), ^{
            //Update done
            [overlayView removeFromSuperview];
            [activityIndicatorView removeFromSuperview];
            [activityIndicatorView stopAnimating];
        });
    });

NEVER forget that all UI processing must be done on the main thread. That's why after finishing data loading and processing, we call dispatch_async again but with "dispatch_get_main_queue()"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top