' MBProgressHUD需要在主线程上访问。' - 斯威夫特3

时间:2016-11-30 16:14:44

标签: ios swift multithreading mbprogresshud dispatch-async

我正在获取MBProgressHUD需要在主线程上访问。'一旦页面加载来自Web服务的数据,隐藏MBProgressHUD时出错。 请帮我解决这个问题。从现在开始几个小时就陷入了这个问题。 我的代码是:

                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   }

1 个答案:

答案 0 :(得分:2)

您试图在所有错误处理中从后台隐藏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()
}

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