如何使用接近传感器切换割炬灯?

时间:2015-10-25 18:11:01

标签: ios swift proximity

到目前为止,在我的代码中,当接近传感器启用时,我可以打开手电筒灯,但是我无法调整我的代码,以便在禁用接近时,手电筒指示灯熄灭。

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")
    }
}

1 个答案:

答案 0 :(得分:0)

通知中的std::cin.clear 始终是UIDevice,因此您的测试毫无意义。问题是您没有检查用户是否接近。收到对设备的引用后,您需要检查其object属性; 是您测试所需的基础。