[英]Swift MKMapView KVO
我试图为我的用户当前位置创建键值观察,但是我无法获得KVO触发任何信息的方法。 设置了mapView的委托。
//add observer here
self.mapView.addObserver(self, forKeyPath: "userLocation", options: NSKeyValueObservingOptions.new, context: nil)
//my method
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print(keyPath!)
}
如果您想知道当前位置何时更改,可以尝试CLLocationManager类并使用他的委托方法
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation])
希望对您有所帮助:)
使用CLLocationManager
:
class ViewController: UIViewController, CLLocationManagerDelegate {
// You must hold a strong reference to the location manager so make it an instance property
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
// Check your app's authorization status
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways:
// Authorized, start tracking location
self.startUpdatingLocation()
case .notDetermined:
// Not authorized, ask for permission. You can also replace this with
// locationManager.requestAlwaysAuthorization() if your app needs it
locationManager.requestWhenInUseAuthorization()
default:
print("permission denied")
break;
}
}
// MARK: -
func startUpdatingLocation() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
self.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let lastLocation = locations.last else {
return
}
// now do what you want with the user's location
}
}
请记住将NSLocationWhenInUseUsageDescription
或NSLocationAlwaysUsageDescription
添加到您的Info.plist
以解释为什么您需要知道用户的位置。 还为用户没有授予您访问手机位置的权限的情况做准备-您必须在知道用户位置的情况下决定应用程序的哪一部分可以运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.