Hey I'm trying to use the proximity sensor to increase a value, but when I start the function, it crash's. This is my Code, can someone help me?
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)
}
}
I think you might be using old syntax for swift. I have tried to use proximity using below code and is working without crash.
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()
}
}
}