Search code examples
swiftcameraproximitysensor

Proximity Senzor addNotification call function mutliple times


I activated the proximity senzor in application and now the function is calling multiple times.

I don't know what is wrong. Can you help me?

    //MARK:- Activate Proximity Sensor
func activateProximitySensor() {
    proximitySenzorActionStatus = true
    device.isProximityMonitoringEnabled = true
    if device.isProximityMonitoringEnabled {
        NotificationCenter.default.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: device)
        NotificationCenter.default.addObserver(self, selector: #selector(proximityStateDidChange), name:UIDevice.proximityStateDidChangeNotification, object: device)
    }
}
func deactivateProximitySenzor() {
    proximitySenzorActionStatus = false
    device.isProximityMonitoringEnabled = false
    NotificationCenter.default.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: device)
}

The methos in now called for 3 times:

 @objc func proximityStateDidChange(notification: NSNotification) {
 print("proximityStateDidChange")}

I activated the senzor in

viewWillAppear

and remove in

viewWillDisappear


Solution

  • You need to calculate the time of flight between every occlusion of the sensor.