我正在尝试从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()
方法...... 感谢您的帮助。