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

时间:2014-11-29 21:22:46

标签: ios swift xcode6 flashlight

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

13 个答案:

答案 0 :(得分:89)

更新#1:torchActive并未返回预期值;可能是因为它已modified}

更新#2:对于Swift 2.0

要将闪光灯从开启切换到关闭(不仅仅是#34;在"如疯牛病的回答中),您可以使用以下方法:

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

我使用嵌套的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)
    }
}

原始答案:

要将闪光灯从开启切换到关闭(不仅仅是#34;在"如疯牛病的回答中),您可以使用以下方法:

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

答案 1 :(得分: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)
        }
    }

答案 2 :(得分:25)

更新了Swift 4答案:

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

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

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

toggleTorch(on: true)

toggleTorch(on: false)

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

他们使用AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo),但这会产生错误,说defaultDevice不存在。所以我将其更改为AVCaptureDevice.default(for: AVMediaType.video)

答案 3 :(得分: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")
        }
    }
}

答案 4 :(得分:6)

像这样:

 func turnTorchOn(){

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


}

答案 5 :(得分: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)
            }
        }
    }
}

答案 6 :(得分:3)

Swift 4 的解决方案条件火炬可用或不可用

# array([ 100.        ,  101.5       ,  101.906     ,  104.046026  ,
#         100.82059919,  103.24029357,  102.41437123])

解决方案是@Joshua Dance@Lance

的组合

答案 7 :(得分:1)

快速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 captureDevice.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel) }
        device.unlockForConfiguration()
    } catch {
        print("Torch can't be used")
    }
}

如评论中所述,您还可以在打开时更改割炬的水平,我觉得非常方便。

答案 8 :(得分:0)

Swift 4.2

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

    if (device.hasTorch) {
        do {
            try device.lockForConfiguration()
            let torchOn = !device.isTorchActive
            try device.setTorchModeOn(level: 1.0)
            device.torchMode = torchOn ? AVCaptureDevice.TorchMode.on : AVCaptureDevice.TorchMode.off
            device.unlockForConfiguration()
        } catch {
            print(error.localizedDescription)
        }
    }
}

答案 9 :(得分:0)

Swift版本5.2.4

    func toggleFlash(on: Bool ) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else { return }
        
        do {
            try device.lockForConfiguration()
            
            device.torchMode = on ? .on : .off
            if on {
                try device.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel)
            }
            
            device.unlockForConfiguration()
        } catch {
            print("Error: \(error)")
        }
    }

答案 10 :(得分:0)

SwiftUI

// TorchState.swift

import SwiftUI
import AVFoundation

class TorchState: ObservableObject {
    
    @Published var isOn: Bool = false {
        didSet {
            toggleTorch(isOn)
        }
    }
    
    private func toggleTorch(_ isOn: Bool) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else { return }
        
        do {
            try device.lockForConfiguration()
            
            device.torchMode = isOn ? .on : .off
            
            if isOn {
                try device.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel)
            }
            
            device.unlockForConfiguration()
        } catch {
            print("Error: \(error)")
        }
    }
}

示例(iOS 14.0):

//ContentView.swift

import SwiftUI

struct ContentView: View {
    @StateObject var torchState = TorchState()
    
    var body: some View {
          Toggle(isOn: $torchState.isOn) {
                Text("Torch")
          }
    }
}
        

答案 11 :(得分:0)

重构。斯威夫特 5.4

import AVFoundation


extension UIDevice {
    
    static func toggleFlashLight() {
        guard let device = AVCaptureDevice.default(for: AVMediaType.video),
              device.hasTorch else { return }
        do {
            try device.lockForConfiguration()
            try device.setTorchModeOn(level: 1.0)
            device.torchMode = device.isTorchActive ? .off : .on
            device.unlockForConfiguration()
        } catch {
            assert(false, "error: device flash light, \(error)")
        }
    }

}

答案 12 :(得分:-1)

Swift 4.1

@objc func Flash() {
        let device = AVCaptureDevice.default(for: AVMediaType.video)
        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)
            }
        }
    }