问题描述
嘿,我试图使用接近传感器来增加一个值,但是当我启动该功能时,它崩溃了。这是我的密码,有人可以帮我吗?
func proximityChanged(notification: NSNotification) {
let device = notification.object as? UIDevice
if device?.proximityState == true {
print("\(device) detected!")
count += 1
updateCountLabel()
} else {
print("Error")
}
}
func activateProximitySensor() {
let device = UIDevice.current
device.isProximityMonitoringEnabled = true
if device.isProximityMonitoringEnabled {
NotificationCenter.default.addobserver(self,selector: Selector(("proximityChanged:")),name: NSNotification.Name(rawValue: "UIDeviceProximityStateDidChangeNotification"),object: device)
}
}
解决方法
我认为您可能正在使用旧语法来快速处理。我尝试使用下面的代码使用接近度,并且没有崩溃。
func activateProximitySensor() {
let device = UIDevice.current
device.isProximityMonitoringEnabled = true
if device.isProximityMonitoringEnabled {
NotificationCenter.default.addObserver(self,selector: #selector(proximityChanged(notification:)),name: UIDevice.proximityStateDidChangeNotification,object: device)
}
}
@objc func proximityChanged(notification: NSNotification) {
if let device = notification.object as? UIDevice {
if device.proximityState {
print("\(device) detected!")
count += 1
updateCountLabel()
}
}
}