Search code examples
objective-cobjective-c-blocksmbprogresshud

UI issues while using blocks


I am using MBProgressHUD to display a loading indicator on my app. When i want to change something at UI or i open a new screen inside block, i only see a blank white screen. Does anyone has an idea what am i missing in my code?

-(void)doSomething:(id)sender
{
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];

HUD.delegate = self;
HUD.labelText = @"Please wait";
[HUD showAnimated:YES whileExecutingBlock:^{
NSDictionary* dictReturn = [ServerApi getItemDetails::itemId userId:userId;
NewScreenController* vc = [[NewScreenController alloc]init];
[self presentViewController:vc animated:YES completion:nil];
}];    
}

Solution

  • MBProgressHUD doesn't execute the block in the main thread. That's why you shouldn't change UI there at all.

    You should use the method with a completionBlock instead.

    - (void)doSomething:(id)sender {
         HUD = [[MBProgressHUD alloc] initWithView:self.view];
         [self.view addSubview:HUD];
    
         HUD.delegate = self;
         HUD.labelText = @"Please wait";
    
         dispatch_block_t executionBlock = ^{
            self.dictReturn = [ServerApi getItemDetails:itemId userId:userId];
         };
    
         void (^completionBlock)() = ^{
             NewScreenController *vc = [[NewScreenController alloc] init];
             [self presentViewController:vc animated:YES completion:nil];
         };
    
         [HUD showAnimated:YES
       whileExecutingBlock:executionBlock
           completionBlock:completionBlock];
    }