Creating Start and Stop Functions for MBProgressHUD

830 views Asked by At

I am trying to create two functions. One to start a progressHUD and one to stop the hud. I am creating this inside an extension of UIViewController. The functions are below:

func startProgressHUD() {
    let spinningActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
    spinningActivity.label.text = "Loading"
}

func stopProgressHUD() {
    DispatchQueue.main.async {
        MBProgressHUD.hide(for: self.view, animated: true)
    }
}

The first function works fine when called -> the HUD starts. However, when I call the stop function, the HUD never stops. According to the description, the hide function I call inside my stop function hides the top-most HUD in the view. I only have one HUD open in the view, but the HUD never stops.

If I use:

func stopProgressHUD() {
    DispatchQueue.main.async {
        MBProgressHUD.hideAllHUDs(for: self.view, animated: true)
    }
}

I have no problem, but the hideAllHUDs function is deprecated -> the warning states, 'store references when using more than one HUD per view'.

How do I get the HUD to stop?

2

There are 2 answers

0
Chan Jing Hong On BEST ANSWER

Declare your spinningActivity as a global variable in your ViewController. Anytime when a HUD is needed you can do self.spinningActivity = MBProgressHUD.showAdded(to: self.view, animated: true). And when you don't need it anymore, self.spinningActivity?.hide()

0
Gurinder Batth On

Declare the MBProgressHUD Globally and then show and hide it. It will definitely work