So far in my code, I am able to turn on the torch light when the proximity sensor is enabled, but I am having trouble adjusting my code to make it so that when the proximity is disabled, the torch light turns off.
func proximityChanged(notification: NSNotification) {
if let device = notification.object as? UIDevice {
print("\(device) detected!")
toggleTorch(on: true)
} else {
//This is the line of code I need help with specifically.
toggleTorch(on: false)
}
}
func activateProximitySensor() {
let device = UIDevice.currentDevice()
device.proximityMonitoringEnabled = true
if device.proximityMonitoringEnabled {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "proximityChanged:", name: "UIDeviceProximityStateDidChangeNotification", object: device)
}
}
func toggleTorch(on on: Bool) {
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
if device.hasTorch {
do {
try device.lockForConfiguration()
if on == true {
device.torchMode = .On
} else {
device.torchMode = .Off
}
device.unlockForConfiguration()
} catch {
print("Torch could not be used")
}
} else {
print("Torch is not available")
}
}