在GMSMapView中添加和删除KVO“myLocation”的观察者

问题描述 投票:3回答:2

我搜索了所有可能的解决方案,但找不到确切的解决方案。我的问题是:我正在使用导航控制器和带有GMSMapView的viewcontroller。当我从GMSMapView导航到其他一些视图时,应用程序崩溃时出现了“GMSMapView类的实例0x7f9b79c53c20被解除分配,而键值观察者仍然注册了它”。

但是,如果我尝试在viewwilldisappear或deinit中删除观察者,则应用程序再次崩溃并出现异常“无法删除关键路径”myLocation“的观察者,因为它未注册为观察者。

任何人都可以帮助解决最佳解决方案这是我的代码:

override func viewDidLoad() {

open.target = self.revealViewController()
open.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

locationManager.delegate = self
mapView.delegate = self

if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
locationManager.requestWhenInUseAuthorization()
}
 mapView.myLocationEnabled = true

placesClient = GMSPlacesClient()  
}

override func viewWillAppear(animated: Bool) {

    mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)

}

deinit{
removeObserver(self, forKeyPath: "myLocation", context: nil)

}
 override func viewWillDisappear(animated: Bool) {


   // removeObserver(self, forKeyPath: "myLocation")
}

 override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if !didFindMyLocation {
        let myLocation: CLLocation = change[NSKeyValueChangeNewKey] as CLLocation
        mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 15.0)
        mapView.settings.myLocationButton = true
        didFindMyLocation = true
    }
}
ios swift xcode6 key-value-observing gmsmapview
2个回答
0
投票

我已经弄明白了这个问题。实际上我担心的是我使用removeObserver(self,forKeyPath:“myLocation”,context:nil)而不是mapView.removeObserver(self,forKeyPath:“myLocation”,context:nil)


0
投票

基于Swift 3.2+的新KVO闭包是这样的:

class myCustomView: UIView {
    let camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 52.5067614, longitude: 13.2846524), zoom: 10, bearing: 0, viewingAngle: 0)
    lazy var mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    private var observation: NSKeyValueObservation?

    func startObserving() {
       self.observation = self.mapView.observe(\.myLocation, options: [.new, .old], changeHandler: { _, change in
                guard let newLocation = change.newValue else { return }
                //Do something with newlocation
            })
    }
}

在任何地方调用startObserving()函数。

使观察者失效不是强制性的,您可以让它超出范围。当你想要使它无效时,只需:

self.observation?.invalidate()
© www.soinside.com 2019 - 2024. All rights reserved.