mat mat - 2 years ago 148
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 {
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)


dispatch_async(dispatch_get_global_queue(priority, 0 )){



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
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

override func viewWillAppear(animated: Bool) {



Everything works except that when the JSON dictionary is empty, meaning that there no offers the
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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download