邻近监控始终返回false

时间:2018-08-28 12:15:12

标签: swift

我正在尝试检测UIDevice.current.proximityState,但是尽管将false设置为true,但它总是返回UIDevice.current.isProximityMonitoringEnabled,并且在我检查时将其打印为true。有任何想法吗?

在iPhone X和6S上使用此代码可获得相同的结果。

在计时器上运行以下代码

UIDevice.current.isProximityMonitoringEnabled = true
print("enabled: \(UIDevice.current.isProximityMonitoringEnabled)") // prints true
print("state: \(UIDevice.current.proximityState)") // always prints false, even when sensor is covered.

任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

您检查主线程上的状态吗?

    var myTimer: Timer!

override func viewDidLoad() {
    super.viewDidLoad()

    myTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)

}

@objc func runTimedCode() {
    DispatchQueue.main.async {
        UIDevice.current.isProximityMonitoringEnabled = true
        print("enabled: \(UIDevice.current.isProximityMonitoringEnabled)") // prints true
        print("state: \(UIDevice.current.proximityState)")
    }
}

它可以在iPhone X上使用

答案 1 :(得分:0)

我很确定这是xcode beta或iOS beta的错误。

有时注册完全相同的代码,有时不注册。非常令人困惑。

如果我发现有什么问题,我会更新此答案,但暂时将其视为错误。

答案 2 :(得分:0)

我认为您可以向近距离更改事件添加侦听器。它对我有用

override func viewWillAppear(_ animated: Bool) {
  // other setup
  UIDevice.current.isProximityMonitoringEnabled = true
}

override func viewDidLoad() {
  // other setup
  NotificationCenter.default.addObserver(self, selector: #selector(self.notifyProximityChange), name: .UIDeviceProximityStateDidChange, object: nil)
}

@objc notifyProximityChange() {
    if UIDevice.current.proximityState {
        print("And it's closed to your face")
    } else {
        print("not anymore")
    }
}

别忘了在生命周期结束时删除观察者

enter image description here