我首先建议一些事情:
stopUpdatingLocation
在表演之前打电话reverseGeocodeLocation
.
您正在完成处理程序关闭stopUpdatingLocation
内部调用reverseGeocodeLocation
.问题在于它以异步方式运行,因此didUpdateLocations
可能在中间期间接收额外的位置更新.通常,当您第一次启动位置服务时,您将获得许多更新,通常会提高准确性(例如,horizontalAccuracy
值越来越小).如果在启动异步地理编码请求之前关闭位置服务,则可以最大限度地减少此问题.
您还可以添加添加distanceFilter
中viewDidLoad
,将尽量减少对委托方法重复的调用:
locationManager.distanceFilter = 1000
您可以使用自己的状态变量来检查是否已启动反向地理编码过程.例如:
private var didPerformGeocode = false func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // if we don't have a valid location, exit guard let location = locations.first where location.horizontalAccuracy >= 0 else { return } // or if we have already searched, return guard !didPerformGeocode else { return } // otherwise, update state variable, stop location services and start geocode didPerformGeocode = true locationManager.stopUpdatingLocation() CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in let placemark = placemarks?.first // if there's an error or no placemark, then exit guard error == nil && placemark != nil else { print(error) return } let city = placemark?.locality ?? "" let state = placemark?.administrativeArea ?? "" self.navigationBar.title = ("\(city), \(state)") self.usersLocation = ("\(city), \(state)") print(self.usersLocation) self.refreshPosts() } }