cuốn sách gpt4 ai đã làm

ios - 如何检查 locationManager 是否更新了当前位置?

In lại Tác giả: Walker 123 更新时间:2023-11-28 08:13:19 25 4
mua khóa gpt4 Nike

我想在启动时显示用户的当前位置,然后继续跟踪他们的位置但停止以当前位置为中心。我的想法是在viewDidLoad()中以当前位置为中心,但是我不知道如何等待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)
}

câu trả lời hay nhất

您只需在初始化 currentLocation 的委托(delegate)方法 didUpdateLocations gọi vào animateMap(currentLocation!) chức năng.

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

关于ios - 如何检查 locationManager 是否更新了当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177326/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress