如何检查locationManager是否更新了当前位置?
问题描述:
我想在启动时显示用户的当前位置,然后继续跟踪他们的位置,但不要集中在当前位置。我的想法是以viewDidLoad()中的当前位置为中心,但我不知道如何等待locationManager在居中之前更新当前位置。这里是我的代码的相关部分:如何检查locationManager是否更新了当前位置?
var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// wait for currentLocation to be updated
animateMap(currentLocation!)
}
mapView.showsUserLocation = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
}
func animateMap(_ location: CLLocation) {
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
mapView.setRegion(region, animated: true)
}
答
你需要简单地调用在委托方法didUpdateLocations
animateMap(currentLocation!)
功能你在哪里初始化currentLocation
。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
animateMap(currentLocation!)
//Either Call `stopUpdatingLocation()`
locationManager.stopUpdatingLocation()
//Or you can create one boolean property with default value false and compare it inside this method
if !animatedFlag {
animateMap(currentLocation!)
animatedFlag = true
}
}
var animatedFlag = false
答
// MARK: - 位置lattitude东经方法委托方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if locationManager.location != nil
{
let locValue = (locationManager.location?.coordinate)!
lat = locValue.latitude
long = locValue.longitude
}
}
答
在didUpdateLocations委托方法中调用animateMap函数,而不是在viewDidLoad中调用。而且,只允许地图第一次居中。你可以为你一些布尔变量。
var isLocationUpdated = false
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
if (!isLocationUpdated)
{
animateMap(currentLocation!)
isLocationUpdated = true
}
}
+0
是的。你做了同样的事情。只有在我发布我的消息后,我才看到你的回答 – MBN
但是这也会调用animateMap,它以当前位置为中心,每当发生位置更新时,对吧?我不希望发生这种情况。我只想在启动时集中到当前位置。 – Asteria
@Asteria然后你可以停止位置管理器来更新它,或者你可以使用可以创建一个适合你的布尔实例属性。 –
这样做了。谢谢! – Asteria