Search code examples
iosspinnersleepnsthread

Sleep function in iOS with Spinner


I have a spinner function to start and stop from beginning of process to end. But since process takes milliseconds, i can't really keep spinner turning.

[NSThread sleepForTimeInterval:2.0]; //method 1
sleep(2); //method2

Then i used Sleep methods to standby the code and let spinner turn, but it stops the Thread, then spinner will stop as well. This is the code:

if (indexPath.row == 1)
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //spinner starts

    EmployeeDataSource *aaa=[[EmployeeDataSource alloc]init];
    [aaa Logout: ^(BOOL results){
        if(results == YES){

        [NSThread sleepForTimeInterval:2.0]; //sleeping thread

        //if logout succesfull go to login page
        LoginViewController *lv = [self.storyboard instantiateViewControllerWithIdentifier:@"loginsb"];

            [self presentViewController:lv animated:NO completion:nil];

            [MBProgressHUD hideAllHUDsForView:self.view animated:YES]; //spinner ends

        }
        else{

            NSLog(@"logout not succesfull");
        }           
}];

I want [MBProgressHUD showHUDAddedTo:self.view animated:YES]; to work for 2 seconds at least, but it ends in less than a second since normal process is fast? How can i extend this time, sleep method seems not suitable. Do you have any idea? Thank you.


Solution

  • i think you should do your stuff after some delay. for that please use this

    [self performSelector:@selector(method) withObject:nil afterDelay:1.0];
    

    here Delay is in second, so you can set it accordingly.

    Or you can go with this as well.

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //Do you stuff here...
        });
    

    May this help you.