如何在swift中打开和关闭手电筒?

Lac*_*tan 46 ios flashlight swift xcode6

我想在Swift中为我的应用添加手电筒功能.我怎么能这样做呢?

Lyn*_*ott 99

更新#1: (torchActive没有返回预期值,这或许是因为它已经修改)

更新#2:适用于Swift 2.0

要将闪光灯从开启切换到关闭(不仅仅是疯狂猪的答案中的"开启"),您可以使用以下方法:

func toggleFlash() {
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if (device.hasTorch) {
        do {
            try device.lockForConfiguration()
            if (device.torchMode == AVCaptureTorchMode.On) {
                device.torchMode = AVCaptureTorchMode.Off
            } else {
                do {
                    try device.setTorchModeOnWithLevel(1.0)
                } catch {
                    print(error)
                }
            }
            device.unlockForConfiguration()
        } catch {
            print(error)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用嵌套的do-catch块来从注释中实现Awesomeness的建议.这样,即使try device.setTorchModeOnWithLevel(1.0)失败,设备也会正确解锁以进行配置.

更新#3:对于Swift 4:

(我根据个人喜好编辑了一下代码)

func toggleFlash() {
    guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
    guard device.hasTorch else { return }

    do {
        try device.lockForConfiguration()

        if (device.torchMode == AVCaptureDevice.TorchMode.on) {
            device.torchMode = AVCaptureDevice.TorchMode.off
        } else {
            do {
                try device.setTorchModeOn(level: 1.0)
            } catch {
                print(error)
            }
        }

        device.unlockForConfiguration()
    } catch {
        print(error)
    }
}
Run Code Online (Sandbox Code Playgroud)

原始答案:

要将闪光灯从开启切换到关闭(不仅仅是疯狂猪的答案中的"开启"),您可以使用以下方法:

func toggleFlash() {
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if (device.hasTorch) {
        device.lockForConfiguration(nil)
        let torchOn = !device.torchActive
        device.setTorchModeOnWithLevel(1.0, error: nil)
        device.torchMode = torchOn ? AVCaptureTorchMode.On : AVCaptureTorchMode.Off
        device.unlockForConfiguration()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为`setTourchModeOnWithLevel`调用需要位于其自己的try块中,以便在出现问题时可以解锁设备进行配置。`do {尝试device.setTorchModeOnWithLevel(1.0)} catch {device.unlockForConfiguration()}` (2认同)

gpi*_*ler 26

我已经更新了@Lyndsey Scott对Swift 2.0的最佳答案

let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if (device.hasTorch) {
        do {
            try device.lockForConfiguration()
            if (device.torchMode == AVCaptureTorchMode.On) {
                device.torchMode = AVCaptureTorchMode.Off
            } else {
                try device.setTorchModeOnWithLevel(1.0)
            }
            device.unlockForConfiguration()
        } catch {
            print(error)
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 对于新手(像我一样),我想补充一点,你需要在视图控制器swift文件的顶部包含'import AVFoundation'. (4认同)

Jos*_*nce 25

更新了Swift 4答案:

func toggleTorch(on: Bool) {
    guard 
        let device = AVCaptureDevice.default(for: AVMediaType.video),
        device.hasTorch
    else { return }

    do {
        try device.lockForConfiguration()
        device.torchMode = on ? .on : .off                    
        device.unlockForConfiguration()
    } catch {
        print("Torch could not be used")
    }
}
Run Code Online (Sandbox Code Playgroud)

然后实际打开或关闭它,调用函数并传入一个true或false布尔值.

toggleTorch(on: true)toggleTorch(on: false)

我从Hacking with Swift得到了这个答案,但是他们的例子中有一个错误.

他们使用AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)但这会产生一个错误defaultDevice,说不存在.所以我改成了AVCaptureDevice.default(for: AVMediaType.video)


Ale*_*cci 9

斯威夫特 5

该解决方案已经由许多人编写,但我还想提出我在项目中提出的更简洁的解决方案:

func toggleTorch(on: Bool) {
    guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
    guard device.hasTorch else { print("Torch isn't available"); return }

    do {
        try device.lockForConfiguration()
        device.torchMode = on ? .on : .off
        // Optional thing you may want when the torch it's on, is to manipulate the level of the torch
        if on { try device.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel.significand) }
        device.unlockForConfiguration()
    } catch {
        print("Torch can't be used")
    }
}
Run Code Online (Sandbox Code Playgroud)

正如评论中提到的,您还可以在打开时更改手电筒级别,我觉得这非常方便。

同时导入 AVFoundation 以使用火炬。


Chu*_*y47 7

对于swift 3

func toggleFlash() {
    if let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo), device.hasTorch {
        do {
            try device.lockForConfiguration()
            let torchOn = !device.isTorchActive
            try device.setTorchModeOnWithLevel(1.0)
            device.torchMode = torchOn ? .on : .off
            device.unlockForConfiguration()
        } catch {
            print("error")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


mad*_*pig 6

像这样:

 func turnTorchOn(){

    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if device.hasTorch {
        device.lockForConfiguration(nil)
        device.setTorchModeOnWithLevel(1.0, error: nil)
        device.unlockForConfiguration()
    }


}
Run Code Online (Sandbox Code Playgroud)


Lan*_*nce 5

对于xcode 9.1,swift 4(如果没有火炬,则更新为不崩溃):

   func toggleFlash() {
    let device = AVCaptureDevice.default(for: AVMediaType.video)

    if (device != nil) {
        if (device!.hasTorch) {
            do {
                try device!.lockForConfiguration()
                    if (device!.torchMode == AVCaptureDevice.TorchMode.on) {
                        device!.torchMode = AVCaptureDevice.TorchMode.off
                    } else {
                        do {
                            try device!.setTorchModeOn(level: 1.0)
                            } catch {
                                print(error)
                            }
                    }

                    device!.unlockForConfiguration()
            } catch {
                print(error)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)