I have a class method that makes an asynchronous API network call which in turn calls an escaping closure that finally calls UITableView.reloadData(). But I am getting an error message suggesting reloadData() cannot execute on this thread but I need it to execute when the countySites variable has been set from a call to sortByDistance(). How can I get reloadData() to execute within this escaping closure?

I have tried placing the call to reloadData() in the closure but I get the error message;

Main Thread Checker: UI API called on a background thread: -[UITableView reloadData]
PID: 3608, TID: 2897278, Thread name: (none), Queue name: NSOperationQueue 0x283d59d60 (QOS: UNSPECIFIED), QoS: 0
Backtrace:
            distanceAPI.getDistanceURLSession( url: distanceAPIURL) { (distances) in
                for siteIndex in 0 ..< self.countySites.count {

                    self.countySites[siteIndex].distance = distances![siteIndex]

                }
                self.countySites = self.sortByDistance(sites: self.countySites)
                for site in self.countySites {
                    print(site.distance)
                }

                self.tableView.reloadData()

            }

I get the error message shown above plus UITableView.reloadData() must be used from main thread only reported in Xcode.

0 Answers