Ios 如何检查locationManager是否已更新当前位置?
我想在启动时显示用户的当前位置,然后继续跟踪他们的位置,但不要以当前位置为中心。我的想法是以viewDidLoad()中的当前位置为中心,但我不知道如何等待locationManager在居中之前更新当前位置。以下是我的代码的相关部分:Ios 如何检查locationManager是否已更新当前位置?,ios,swift,mapkit,Ios,Swift,Mapkit,我想在启动时显示用户的当前位置,然后继续跟踪他们的位置,但不要以当前位置为中心。我的想法是以viewDidLoad()中的当前位置为中心,但我不知道如何等待locationManager在居中之前更新当前位置。以下是我的代码的相关部分: var currentLocation : CLLocation? @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad()
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)
}
//标记:-位置点阵长度方法委托方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if locationManager.location != nil
{
let locValue = (locationManager.location?.coordinate)!
lat = locValue.latitude
long = locValue.longitude
}
}
您只需在委托方法
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
在didUpdateLocations委托方法中调用animateMap函数,而不是在viewDidLoad中调用。并且,仅允许贴图第一次居中。你可以给你一些布尔变量
var isLocationUpdated = false
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
if (!isLocationUpdated)
{
animateMap(currentLocation!)
isLocationUpdated = true
}
}
但这也会调用animateMap,它以当前位置为中心,每次位置更新发生时,对吗?我不想发生这种事。我只想在启动时以当前位置为中心。@Asteria然后您可以停止位置管理器进行更新,或者您可以使用创建一个适合您的布尔实例属性。这样做了。非常感谢。对你也做了同样的事。我是在贴出我的答案后才看到你的答案的。