使用以下代码,我的 currentLat 和 currentLong 不会更新到第一个位置之外。 locations 永远不会超过 1 个项目,而且总是完全相同。
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let loc: CLLocation = locations[locations.count - 1]
currentLat = loc.coordinate.latitude
currentLong = loc.coordinate.longitude
}
我一直在做的所有搜索只显示了如果它根本不起作用,如何让它起作用,但这确实起作用,但只有一次。
我希望它的工作方式是不断更新 GPS 坐标,并在位置更新时关闭该委托(delegate)。该位置是否一直在更新?我认为这是由于术语“startUpdatingLocation()”和“stopUpdatingLocation()”所致。我是否试图错误地使用它?
就像我说的,它是第一次工作,所以它加载和启动都很好,允许权限,info.plist 有必要的条目。
最佳答案
当您想更新您的位置时,您应该在获得新位置后停止现有更新。您可以在 didUpdateLocations: 方法中使用 stopUpdatingLocation() 来执行此操作。
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// This should match your CLLocationManager()
locManager.stopUpdatingLocation()
let loc: CLLocation = locations[locations.count - 1]
currentLat = loc.coordinate.latitude
currentLong = loc.coordinate.longitude
}
然后在需要新位置时调用您的 locManager.startUpdatingLocation()。
关于iOS 和 Swift : CLLocationManagerDelegate not updating location coordinates beyond the first location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427774/