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.
first show your hud after your url initialized and right before your task get started
then hide it right after callback block started
you don't have to call
return
after hud gets hidden