在 Swift 中打开/关闭 iPhone LED(闪光灯)? [复制]
Posted
技术标签:
【中文标题】在 Swift 中打开/关闭 iPhone LED(闪光灯)? [复制]【英文标题】:Turn the iPhone LED (flash) on/off in Swift? [duplicate] 【发布时间】:2015-03-11 23:43:11 【问题描述】:我可以使用什么代码通过一个按钮打开/关闭 iPhone 闪光灯(在 Swift 中)。
我是使用 Outlet 还是 Action 进行连接?
感谢所有帮助!
【问题讨论】:
【参考方案1】:Xcode 9 测试版 • Swift 4
import AVFoundation
extension AVCaptureDevice
var isLocked: Bool
do
try lockForConfiguration()
return true
catch
print(error)
return false
func setTorch(intensity: Float)
guard hasTorch && isLocked else return
defer unlockForConfiguration()
if intensity > 0
if torchMode == .off
torchMode = .on
do
try setTorchModeOn(level: intensity)
catch
print(error)
else
torchMode = .off
用法:
import UIKit
import AVFoundation
class ViewController: UIViewController
var device: AVCaptureDevice!
override func viewDidLoad()
super.viewDidLoad()
device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .unspecified)
@IBAction func slider(_ sender: UISlider)
device.setTorch(intensity: sender.value)
Xcode 8.2.1 • Swift 3.0.2
extension AVCaptureDevice
@discardableResult
class func toggleTorch() -> Bool
guard let defaultDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .unspecified)
else
print("early exit")
return false
// Check if the default device has torch
if defaultDevice.hasTorch
print("defaultDevice.hasTorch:", defaultDevice.hasTorch)
// Lock your default device for configuration
do
// unlock your device when done
defer
defaultDevice.unlockForConfiguration()
print("defaultDevice.unlockedForConfiguration:", true)
try defaultDevice.lockForConfiguration()
print("defaultDevice.lockedForConfiguration:", true)
// Toggles the torchMode
defaultDevice.torchMode = defaultDevice.torchMode == .on ? .off : .on
// Sets the torch intensity to 100% if torchMode is ON
if defaultDevice.torchMode == .on
do
try defaultDevice.setTorchModeOnWithLevel(1)
catch
print(error.localizedDescription)
catch
print(error.localizedDescription)
print("defaultDevice.torchMode:", defaultDevice.torchMode == .on)
return defaultDevice.torchMode == .on
class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_:))))
func tap(_ gesture: UITapGestureRecognizer)
if AVCaptureDevice.toggleTorch()
print("TORCH IS ON")
else
print("TORCH IS OFF")
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
【讨论】:
以上是关于在 Swift 中打开/关闭 iPhone LED(闪光灯)? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何在 iOS Swift 或 Objective C 中检测 iPhone 卷访问 [关闭]