Ios cellForRowAtIndexPath很晚才被调用

Ios cellForRowAtIndexPath很晚才被调用,ios,swift,uitableview,swift3,Ios,Swift,Uitableview,Swift3,我试图根据用户位置从OpenWeatherMapAPI获取JSON数据,并将其显示在tableview中 首先,我只是初始化我的表视图: init(_ coder: NSCoder? = nil) { self.tableView = UITableView() self.locationManager = CLLocationManager() } 然后在viewDidLoad中调用函数launchLocationOperations(),以获取用户的位置: func lau

我试图根据用户位置从OpenWeatherMapAPI获取JSON数据,并将其显示在tableview中

首先,我只是初始化我的表视图:

init(_ coder: NSCoder? = nil) {
    self.tableView = UITableView()
    self.locationManager = CLLocationManager()
}
然后在viewDidLoad中调用函数
launchLocationOperations()
,以获取用户的位置:

func launchLocationOperations() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}
在我的代表中:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    self.locationManager.stopUpdatingLocation()
    let locationArray = locations as NSArray
    let currentLocation = locationArray.lastObject as! CLLocation
    if self.currentCoordinates == nil ||
        (self.currentCoordinates?.latitude != currentLocation.coordinate.latitude
            ||
            self.currentCoordinates?.longitude != currentLocation.coordinate.longitude) {
        self.currentCoordinates = currentLocation.coordinate
        self.hasLoadedCoordinates = true
        self.fetchWeatherInformations()
    }
}
然后调用
fetchWeatherInformation()

displayi()
中:

所以我这里有两个问题:

  • 首先,
    didUpdateLocation
    被多次调用,即使我在进入函数时要求
    stopUpdateLocation()
  • 其次,
    cellforrowatinexpath
    被调用的时间非常晚,大约晚了5秒。我不知道为什么会发生这种情况,因为其他
    数据源
    /
    委托
    方法在进入
    displayi()
    后会立即被调用

感谢您的帮助。

displayUI()中设置数据源和委托有什么好处?您应该在创建表视图后立即(一次)设置这两个参数,并调用
reloadData()
来更新UI。您是否尝试在DispatchQueue.main.async{self.displayi()}@vadian这样的主线程上调用displayi()方法,我在
viewDidLoad
中设置了
dataSource
delegate
。@Aakash谢谢你的回答,它解决了我的问题!我只是知道我正在尝试从主线程更新外部的UI。。。再次感谢。
func fetchWeatherInformations() {
    // I build my path
    let urlPath = StringUtils.buildUrl(self.currentCoordinates)
    guard let url = URL(string: urlPath) else { return }
    let request = URLRequest(url: url)
    URLSession.shared.dataTask(with: request) { data, _, error in
        do {
            let jsonResponse = try data?.toJSON() as? [String : Any]
            self.openWeatherMapResponse = OpenWeatherMapResponse.convert(jsonResponse: jsonResponse)
            self.displayUI()
        } catch {
            print("Error while fetching JSON response : \(error.localizedDescription)")
        }
    }.resume()
}
func displayUI() {
    tableView.delegate = self
    tableView.dataSource = self
}