在我的应用程序中,我有一个此类用于从服务器获取数据:
class Api{
func loadOffers(completion:(([Offers])-> Void), offer_id: String, offerStatus:String){
let myUrl = NSURL(string: "http://www.myServer.php/api/v1.0/offers.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "offer_id=\(offer_id)&offerStatus=\(dealStatus)&action=show"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
println("error\(error)")
}else{
var err:NSError?
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let dict = jsonObject as? [String: AnyObject] {
if let myOffers = dict["offers"] as? [AnyObject] {
var offers = [Offers]()
for offer in myOffers{
let offer = Offers(dictionary: offer as! NSDictionary)
offers.append(offer)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0 )){
dispatch_async(dispatch_get_main_queue()){
completion(offers)
}
}
}
}
}
}
}
task.resume()
}
}
然后在我的View Controller中加载模型:
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var offers: [Offers]!
func loadModel() {
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "updating your offers..."
offers = [Offers]()
let api = Api()
api.loadOffers(didLoadOffers , offer_id: dealIdent!, offerStatus: "open")
}
func didLoadOffers(offers:[Offers]){
self.offers = offers
self.tableView.reloadData()
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.refreshControl.endRefreshing()
}
override func viewWillAppear(animated: Bool) {
loadModel()
}
}
一切正常,除了当JSON字典为空时,这意味着没有提供
MBProgressHUD
继续旋转。我想停止在事件指示器中添加一个 subview ,该 subview 表示没有报价。任何建议将不胜感激。
我试过了:
if offers.isEmpty{ MBProgressHUD.hideAllHUDsForView(self.view, animated: true) }
并且
if offers == 0 { MBProgressHUD.hideAllHUDsForView(self.view, animated: true) }
但它不起作用
谢谢
最佳答案
发生这种情况是因为您在主队列中设置了HUD,但正尝试从另一个队列中删除HUD。所有与UI相关的更改均应在main_queue()
中完成
尝试使用此代码
dispatch_async(dispatch_get_main_queue(), {
// your code to modify HUD here
});
关于ios - 服务器不返回数据时如何停止MBProgressHUD并添加 subview ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30151270/