Search code examples
objective-ciosxcodeuiviewuiwebview

How show activity-indicator when press button for upload next view or webview?


My first view is looks like  this when i click on button which title is click here to enlarge then i want show activity indicator on the first view and remove when load this view. second view in which image is upload from URL in image view.

but i go back then it show activity indicator which is shown in this view. first view with activity indicator

in first vie .m file i have use this code for action.

-(IBAction)btnSelected:(id)sender{
UIButton *button = (UIButton *)sender;
int whichButton = button.tag;
NSLog(@"Current TAG: %i", whichButton);
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(160,124)]; 
[self.view addSubview:spinner]; 
[spinner startAnimating];

if(whichButton==1)
{
    [spinner stopAnimating];

    first=[[FirstImage alloc]init];
    [self.navigationController pushViewController:first animated:YES];
    [spinner hidesWhenStopped ];

        }} 

in above code i have button action in which i call next view. Now i want show/display activity indicator when view upload. In next view i have a image view in which a image i upload i have declare an activity indicator which also not working. How do that?


Solution

  • Toro's suggestion offers a great explanation and solution, but I just wanted to offer up another way of achieving this, as this is how I do it.

    As Toro said,

    - (void) someFunction
    {
        [activityIndicator startAnimation];
    
        // do computations ....
    
        [activityIndicator stopAnimation];  
    }
    

    The above code will not work because you do not give the UI time to update when you include the activityIndicator in your currently running function. So what I and many others do is break it up into a separate thread like so:

    - (void) yourMainFunction {
        activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
        [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
    
        //Your computations
    
        [activityIndicator stopAnimating];
    
    }
    
    - (void) threadStartAnimating {
        [activityIndicator startAnimating];
    }
    

    Good luck! -Karoly