-1

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")
    }
}
picciano
  • 22,341
  • 9
  • 69
  • 82
D.Khan
  • 1
  • 3

1 Answers1

0

The object in the notification will always be the UIDevice, so your test is pointless. The problem is that you are not checking whether the user is proximate or not. Having receive a reference to the device you need to check its proximityState property; that is the basis you need for your test.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • How would I check for the proximityState property. Would I replace my function for toggleTorch with a check proximityState property? The apple literature isn't too specific on this either. Thank you for your help. – D.Khan Oct 25 '15 at 23:43
  • 2
    I don't know what you mean by the "apple literature". Just read the documentation on the UIDevice class. I'm not going to write your code for you. – matt Oct 25 '15 at 23:51