Alexey K
Alexey K

Reputation: 6723

Swift - how to correctly use MBProgressHUD.h?

I have some functions and I want to show progreeeHUD during they are working

i come up with two functions showing and hiding hud

 func showHud() {
    let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)

and

func hideHud() {
    MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

I tried to do like this

viewDidLoad

showHud()

func1()
func2()
func3()
func4()

showHud()

but this doesnt work, hud is not showing

also i tryed this

@IBAction func goToGame(sender: UIButton) {


    let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    progressHUD.labelText = "Loading..."

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {

        self.JSONRequest()
        self.loadFromDb()
        self.checkForDupl()
        self.saveToDb()

        dispatch_async(dispatch_get_main_queue()) {
            progressHUD.hide(true)
            self.performSegueWithIdentifier("toGameSegue", sender: nil)

        }
    }

the problem here is that viewController, that must be shown after "toGameSegue" doesnt wait for completion of JSONRequest and following and so the app crashes because it doesnt have needed data

Upvotes: 0

Views: 1495

Answers (1)

Saumil Shah
Saumil Shah

Reputation: 2349

Without Block

Try this for Visible:

let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "Loading"

To dismiss the ProgressHUD:

MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

In your case:

@IBAction func goToGame(sender: UIButton) {


    let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    progressHUD.labelText = "Loading..."

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {

        self.JSONRequest()


        dispatch_async(dispatch_get_main_queue()) {

        }
 }

func JSONRequest()
{
        //write it to success block
           self.loadFromDb()
            self.checkForDupl()
            self.saveToDb()
             progressHUD. hide (true)
             self.performSegueWithIdentifier("toGameSegue", sender: nil)
}

Upvotes: 1

Related Questions