假设我有以下代码:
@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)")
}
}
}
}
隐藏添加到self.view
的HUD的正确方法是什么?有没有比添加
dispatch_async(dispatch_get_main_queue()) {
MBProgressHUD.hideHUDForView(self.view, animated: true)
return
}
每个if
和else
分支的代码?
提前致谢。
答案 0 :(得分:1)
首先在您的网址初始化之后和任务开始之前显示您的hud
if let url = NSURL(string: someURL) {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// start the request here
然后在回调块启动后立即隐藏它
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
hud隐藏后你不必打电话给return