Swift MKMapView KVO

时间:2017-02-15 01:16:09

标签: ios swift mapkit key-value-observing

我试图为我的用户当前位置创建一个键值观察,但我无法获得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!)
    }

2 个答案:

答案 0 :(得分:0)

如果您想知道当前位置何时发生变化,可以尝试使用CLLocationManager类并使用他的委托方法

func locationManager(_ manager: CLLocationManager, 
       didUpdateLocations locations: [CLLocation])

我希望它有所帮助:)

答案 1 :(得分:0)

使用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添加NSLocationAlwaysUsageDescriptionInfo.plist,以解释您需要了解用户所在位置的原因。如果用户未授予您访问手机位置的权限,也要做好准备 - 您必须知道应用的哪个部分可以知道用户的位置。