'MBProgressHUD needs to be accessed on the main thread.' - Swift 3

'MBProgressHUD needs to be accessed on the main thread.' - Swift 3

在页面加载来自 Web 服务的数据后,我在隐藏 MBProgressHUD 时收到 'MBProgressHUD needs to be accessed on the main thread.' 错误。 请帮我解决这个问题。几个小时以来一直坚持这个问题。 我的代码是:

                DispatchQueue.main.async {
                    self.spinnerActivity.hide(animated: true)
                    self.tableView.reloadData()
                    self.refreshControl.endRefreshing()
                }

我在 viewDidLoad 中启动了旋转器,如下所示:

    spinnerActivity = MBProgressHUD.showAdded(to: self.view, animated: true);
    spinnerActivity.label.text = "Loading";
    spinnerActivity.detailsLabel.text = "Please Wait!!";

请帮忙

编辑:

这是我的那个视图控制器的全部代码:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var refreshControl: UIRefreshControl!
var spinnerActivity: MBProgressHUD! = nil

override func viewDidLoad() {
    super.viewDidLoad()

    refreshControl = UIRefreshControl()
    refreshControl.tintColor = UIColor.green
    refreshControl.attributedTitle = NSAttributedString(string: "Refreshing", attributes: [NSForegroundColorAttributeName: UIColor.white])
    refreshControl.addTarget(self, action: #selector(ViewController.refresh(sender:)), for: UIControlEvents.valueChanged)
    tableView.addSubview(refreshControl)

    spinnerActivity = MBProgressHUD.showAdded(to: self.view, animated: true);
    spinnerActivity.label.text = "Loading";
    spinnerActivity.detailsLabel.text = "Please Wait!!";

    self.navigationItem.hidesBackButton = true
    let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.back(sender:)))
    self.navigationItem.leftBarButtonItem = newBackButton

    navigationItem.title = city.uppercased()

    self.runWebService()
}

func runWebService(){


    let url = URL(string: "")!// have removed my url

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in // URLSession.shared().dataTask(with: url) { (data, response, error) is now URLSession.shared.dataTask(with: url) { (data, response, error)

        if error != nil {
            self.spinnerActivity.hide(animated: true)
            print(error)
        } else {
            if let urlContent = data {
                do {
                    guard let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] else {
                        self.spinnerActivity.hide(animated: true)
                        return
                    }
                    //processing web service
                    //DispatchQueue.global(qos: .userInitiated).async {
                    DispatchQueue.main.async {
                        self.spinnerActivity.hide(animated: true)
                        self.tableView.reloadData()
                        self.refreshControl.endRefreshing()
                    }
                } catch {
                    self.spinnerActivity.hide(animated: true)
                    print("JSON Processing Failed")
                }
            }
        }
    }
    task.resume()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func back(sender: UIBarButtonItem) {
    _ = navigationController?.popToRootViewController(animated: true)
}

func refresh(sender:AnyObject) {
    //pull to refresh
    self.runWebService()
}

//remaining are table view data source and delegate methods   }

您试图在所有错误处理中从后台隐藏 MBProgressHUD。切换到主线程修复:

func runWebService(){

    let url = URL(string: "http://www.google.com")!// have removed my url

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in // URLSession.shared().dataTask(with: url) { (data, response, error) is now URLSession.shared.dataTask(with: url) { (data, response, error)

        if error != nil {
            DispatchQueue.main.async {
                self.spinnerActivity.hide(animated: true)
            }

            print(error)
        } else {
            if let urlContent = data {
                do {
                    guard let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] else {
                        DispatchQueue.main.async {
                            self.spinnerActivity.hide(animated: true)
                        }
                        return
                    }
                    //processing web service
                    //DispatchQueue.global(qos: .userInitiated).async {
                    DispatchQueue.main.async {
                        self.spinnerActivity.hide(animated: true)
                    }
                } catch {
                    DispatchQueue.main.async {
                        self.spinnerActivity.hide(animated: true)
                    }
                    print("JSON Processing Failed")
                }
            }
        }
    }
    task.resume()
}

** 请注意,我删除了您的一些代码以进行测试。