Best practice to hide the HUD added to view

676 views Asked by At

Suppose that I have the following code:

@IBAction func signInButtonPressed(sender: AnyObject) {
    MBProgressHUD.showHUDAddedTo(self.view, animated: true)

    if let url = NSURL(string: someURL) {

            // ...

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                (data, response, error) in

                if let httpError = error {
                    dispatch_async(dispatch_get_main_queue()) {
                        self.alert("Error", message: "Unable to sign in: \(httpError.localizedDescription)")
                    }
                    return
                }

                var deserializationError: NSError?
                if let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &deserializationError) as? [String: AnyObject] {

                    // ...

                    if let error = customer.error {
                        dispatch_async(dispatch_get_main_queue()) {
                            self.alert("Error", message: error)
                        }
                    } else {
                        // Show other view controller
                    }
                } else {
                    if let unwrappedError = deserializationError {
                        dispatch_async(dispatch_get_main_queue()) {
                            self.alert("Error", message: "Unable to sign in: \(deserializationError)")
                        }
                    }
                }
            }
            task.resume()
        } else {
            if let unwrappedError = serializationError {
                self.alert("Error", message: "Unable to sign in: \(serializationError)")
            }
        }
    }
}

What is the proper way to hide the HUD added to self.view? Is there any more elegant way to do this than adding the

dispatch_async(dispatch_get_main_queue()) {
    MBProgressHUD.hideHUDForView(self.view, animated: true)
    return
}

code to every if and else branches?

Thanks in advance.

1

There are 1 answers

0
kas-kad On BEST ANSWER

first show your hud after your url initialized and right before your task get started

if let url = NSURL(string: someURL) {
    MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    // start the request here

then hide it right after callback block started

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                (data, response, error) in
    dispatch_async(dispatch_get_main_queue()) {
        MBProgressHUD.hideHUDForView(self.view, animated: true)
    }
    // here goes other logic

you don't have to call return after hud gets hidden