mat mat - 6 months ago 26
iOS Question

How to stop MBProgressHUD and add a subview when the server is not returning data

In my app I have this class to get data from my server:

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()
}
}


then in my View Controller I load the model:

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()

}
}


Everything works except that when the JSON dictionary is empty, meaning that there no offers the
MBProgressHUD
keep spinning.enter image description here

I would like stop the activity indicator adding a subview instead which says that there are no offers. Any Suggestion would be greatly appreciated.

I tried:

if offers.isEmpty{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}


and also

if offers == 0 {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}


but it's not working

Thanks

Answer

This might be occurring because you set the HUD in main queue but are trying to remove from another one. All UI related changes should be done in main_queue()

Try using this code

dispatch_async(dispatch_get_main_queue(), { 

  // your code to modify HUD here

});
Comments