MBProgressHUD needs to be accessed on the main thread

713 Views Asked by At

Im getting this error while using MBProgessHUD. I was trying to show an Loading Indicator then my App is loading data from an Api and to stop then the data is displayed on screen.

func getJson(){ 
        let spinningWheel = MBProgressHUD.showAdded(to: self.view, animated: true)
        spinningWheel.label.text = "Loading"
        spinningWheel.detailsLabel.text = "Please wait a moment.."
.
. 
.
.
.
.
. 
DispatchQueue.main.async {
                    self.movieName.isHidden = false
                    self.movieName.text = self.movieNameLabel
                    self.movieDescription.text = self.movieDescriptionLabel
                    self.movieImage.downloadedFrom(url: url2!)
                    spinningWheel.hide(animated: true)
                }
2

There are 2 best solutions below

1
Gereon On

In iOS, all UIKit method calls must be made on the main thread. Enclose all your UIkit usages in DispatchQueue.main.(a)sync calls, like so:

func getJson() {
  DispatchQueue.main.async {
    let spinningWheel = MBProgressHUD.showAdded(to: self.view, animated: true)
    spinningWheel.label.text = "Loading"
    spinningWheel.detailsLabel.text = "Please wait a moment.."
  }
  // actually get JSON
}
0
Shehata Gamal On

The one suspect is that you present/push/segue to that vc from a background thread so this

let spinningWheel = MBProgressHUD.showAdded(to: self.view, animated: true)

will run inside it , so make sure to do the navigation inside the main thread , so the vc life cycle will be in correct place