Proximity Sensor 增加 Notification 多次调用功能

Proximity Senzor addNotification call function mutliple times

我在应用程序中激活了接近传感器,现在该功能被多次调用。

不知道怎么回事。你能帮帮我吗?

    //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)
}

方法中调用了3次:

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

我在

中激活了传感器

viewWillAppear

并在

中移除

viewWillDisappear

您需要计算传感器每次遮挡之间的飞行时间。