1.开启距离传感器功能
UIDevice.current.isProximityMonitoringEnabled = true
2.监听物体靠近或者离开设备的通知
NotificationCenter.default.addObserver(self, selector: #selector(stateChange), name: UIDevice.proximityStateDidChangeNotification, object: nil)
3.通知所调用的方法
@objc func stateChange() -> Void {
// 判断当前是否有物体靠近
if UIDevice.current.proximityState {
print("有")
}else {
print("没有")
}
}
4.移除通知
deinit {
NotificationCenter.default.removeObserver(self)
}