Search code examples
objective-cxcodembprogresshudsdwebimage

MBProgressHUD & SDWebImage - HUD not showing


I'm using SDWebImagePrefetcher to prefetch a list of images off my plist.

I was editing the method trying to alloc a UIViewController which would have shown an MBProgressHUD HUD to indicate the progress.

Problem is that the HUD won't show in any way. Plus, SDWebImagePrefetcher is a NSObject and I don't really know where to init my custom UIViewController and the HUD, due it doesn't have any viewDidLoad or viewWillAppear methods.

I tried to do something like

MyCustomViewController *cv = [[MyCustomViewController alloc]init];
HUD = [[MBProgressHUD alloc]initInView:cv.view];

and didn't work.

I also tried to add an UIAlertView as subView of the viewController in order to see if it worked but it didn't work at all!

Any advice on where to init an UIViewController in a NSObject class in order to show an HUD on the allocated controller would be awesome.


Solution

  • If you want to display a MBProgressHUD from any class it's simple. Just add it to your application's keyWindow. This is the very top level window for your application and it easy to access from anywhere.

    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
    hud.labelText = @"Loading";
    

    And when you want to hide the MBProgressHUD just use

    [hud hide:YES];
    

    Make sure you wait to access the keyWindow until your app's main window has been set up. This occurs at launch. If it is setup programmatically it is in your AppDelegate by calling [window makeKeyAndVisible].