Search code examples
objective-cios5mbprogresshud

Use MBProgressHUD with multiple dispatches


What is the best way get the label to change for HUD on both the processing thread and main thread?

[activitySpinner startAnimating];
    //[HUD setLabelText:@"Connecting"];
    //[HUD showUsingAnimation:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"Connecting1";

        NSString *url = [NSString stringWithFormat:@"my URL", [dataObj.pListData objectForKey:@"API_BASE_URL"], userField.text, passwordField.text];
        NSLog(@"Login: %@",url);
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

        NSError *error;        
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        [HUD setLabelText:@"Processing"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([json objectForKey:@"authToken"] != nil) {
                [HUD setLabelText:@"Logging In"];
                NSLog(@"Found authtoken %@", [json objectForKey:@"authToken"]);
                [dataObj setAuthToken:[json objectForKey:@"authToken"]];
                [dataObj setLocationId:[json objectForKey:@"c_id"]];

                [dataObj setStaffId:[[json objectForKey:@"staffOrRoomsId"] integerValue]];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                [HUD setLabelText:@"Downloading"];

                });

                [self getAllData];
                [self performSegueWithIdentifier:@"segueToRootController" sender:self];


            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:[json objectForKey:@"friendlyErrors"] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];
                alert = nil;
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });


        [activitySpinner stopAnimating];
    });

I've tried the above since if I run the label changing on the main thread it won't change until after all processing is done.

In my viewWillAppear I am setting

HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.delegate = self;

It will show connecting but will not show Processing or downloading.


Solution

  • Actually after testing this on the device I found that it does indeed display Processing and Downloading. It just doesn't show it in the emulator. I guess since it uses the computer processor, it happens so quick.