cellForRowAtIndexPath被调用很晚

时间:2017-01-22 10:37:13

标签: ios swift uitableview swift3

我正在尝试从OpenWeatherMap API获取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()

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()
}

displayUI()

func displayUI() {
    tableView.delegate = self
    tableView.dataSource = self
}

所以我在这里有两个问题:

  • 首先,即使我在进入该功能时要求didUpdateLocations,也会多次调用stopUpdatingLocation()
  • 其次,cellForRowAtIndexPath被称为非常非常晚,比如迟到5秒。我不知道为什么会发生这种情况,因为在输入dataSource之后会立即调用其他delegate / displayUI()方法......

感谢您的帮助。

0 个答案:

没有答案