Proximity sensor in Swift (from Objective-C)
Swift 3 Version
(Based on Eric Aya's answer)
func setProximitySensorEnabled(_ enabled: Bool) {
let device = UIDevice.current
device.isProximityMonitoringEnabled = enabled
if device.isProximityMonitoringEnabled {
NotificationCenter.default.addObserver(self, selector: #selector(proximityChanged), name: .UIDeviceProximityStateDidChange, object: device)
} else {
NotificationCenter.default.removeObserver(self, name: .UIDeviceProximityStateDidChange, object: nil)
}
}
func proximityChanged(_ notification: Notification) {
if let device = notification.object as? UIDevice {
print("\(device) detected!")
}
}
Here's my take on this.
func activateProximitySensor() {
let device = UIDevice.currentDevice()
device.proximityMonitoringEnabled = true
if device.proximityMonitoringEnabled {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "proximityChanged:", name: "UIDeviceProximityStateDidChangeNotification", object: device)
}
}
func proximityChanged(notification: NSNotification) {
if let device = notification.object as? UIDevice {
println("\(device) detected!")
}
}