How to get if an observer is registered in Swift

You're on the right track. Add an isObserving property to your class. Set it to true when you start observing, and set it to false when you stop observing. In all cases check the flag before starting/stopping observing to make sure you are not already in that state.

You can also add a willSet method to the property and have that code start/stop observing when the property changes states.


Main reason: addObserver() is called 1 time (at viewDidLoad or init), but removeObserver() can be called 2 times or more (base on the times viewWillDisappear() was called).

To resolve: move addObserver() to viewWillAppear():

private var didOnce = false

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.mapView.addObserver(self, forKeyPath: "myLocation", options: .new, context: nil)
}

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if(!didOnce){
        if(keyPath == "myLocation"){
            location = mapView.myLocation.coordinate;

            self.mapView.animateToLocation(self.location!);
            self.mapView.animateToZoom(15);
            didOnce = true;
            self.mapView.removeObserver(self, forKeyPath: "myLocation");
        }
    }
}

override func viewWillDisappear(animated: Bool) {
    if(!didOnce){
        self.mapView.removeObserver(self, forKeyPath: "myLocation");
        didOnce = true;
    }
}

Tags:

Ios

Swift