0

Im using the MBProgressHUD to make an overview loading screen while logging out in my ipad app. That progress takes some time because I have to encrypt some bigger files.

Because Im doing it in a background thread and the MBProgressHUD is animating on the main thread, I had to do something to know when my background thread is finished.

As a test, I did it like that:

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDAnimationFade;
hud.labelText = @"Do something...";

[self performSelectorInBackground:@selector(doSomethingElse) withObject:nil];

And method doSomethingElse:

-(void)doSomethingElse
{
    [self encrypt];
    [self performSelectorOnMainThread:@selector(doSomethingElseDone) withObject:nil waitUntilDone:YES];
}

And method doSomethingElseDone:

-(void)logoutInBackgroundDone
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];    
}

The solution works but I think there must be a better way? How can I do that on a better way?

Any help is really appreciated.

NDY
  • 3,527
  • 4
  • 48
  • 63

2 Answers2

2

You can directly dismiss the MBProgressHUD from doSomethingElse method using dispatch_async

-(void)doSomethingElse
{
    [self encrypt];
    dispatch_async(dispatch_get_main_queue(), ^{
         [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • I like that. But there is no possibility to handle the end of the background thread without calling another method? Something like a callback - just that I know when the performSelectorInBackground finished? – NDY Nov 20 '12 at 07:51
  • I accepted it because im using it like that and found no better solution. – NDY Nov 23 '12 at 09:23
  • @Andy: for doing some action at end of the perform selector on background either you need to call a method or post notification. There is no call back mechanism for this. Check this question http://stackoverflow.com/questions/5406803/detect-end-of-performselectorinbackgroundwithobject – Midhun MP Nov 23 '12 at 09:47
  • thank you. Seems to be the best solution. So sad that there is no callback or something like that existing. – NDY Nov 23 '12 at 09:48
0

Create an atomic property you can get to

@property BOOL spinning;

and

- (void)myTask
{
    while ( self.spinning )
    {
        usleep(1000*250); // 1/4 second
    }
}

then use something in your view controller like

HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];

This way the HUD will remove itself when spinning becomes false. The spinner has to be atomic since it will be referenced in a background thread. Whatever you are waiting on can simply set the spinner property to false from any thread to indicate it's done.

This is under ARC.

ahwulf
  • 2,584
  • 15
  • 29