Skip to content

Instantly share code, notes, and snippets.

@hashaam
Created August 24, 2022 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hashaam/7dacb1e066eeee10720b70832a2d670c to your computer and use it in GitHub Desktop.
Save hashaam/7dacb1e066eeee10720b70832a2d670c to your computer and use it in GitHub Desktop.
Turn On/Off Video Camera Torch
/*
Step 1 - Privacy Text for Requesting Camera Permission
Open the Info.plist file as source code and enter the following text in the <dict></dict>:
<key>NSCameraUsageDescription</key>
<string>This app requires camera</string>
*/
// Step 2 - Imports
import AVFoundation
// Step 3 - Check for Camera Permission
let status = AVCaptureDevice.authorizationStatus(for: .video)
switch status {
case .authorized: print("authorized")
case .notDetermined: return .notRequested
default: return .unauthorized
}
// Step 4 - Request for Camera Permission
AVCaptureDevice.requestAccess(for: .video) { granted in
DispatchQueue.main.async {
guard granted else {
print("permission not granted")
return
}
print("authorized")
}
}
// Step 5 - Get Back Camera Capture Device
func getBackVideoCaptureDevice() -> AVCaptureDevice? {
if let tripleCamera = AVCaptureDevice.default(.builtInTripleCamera, for: .video, position: .back) {
return tripleCamera
}
if let dualWideCamera = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back) {
return dualWideCamera
}
if let dualCamera = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) {
return dualCamera
}
if let wideAngleCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) {
return wideAngleCamera
}
return nil
}
// Step 6 - Get Camera Capture Device Input
func getCaptureDeviceInput(captureDevice: AVCaptureDevice) -> AVCaptureDeviceInput? {
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
return captureDeviceInput
} catch let error {
print("Failed to get capture device input with error \(error)")
}
return nil
}
// Step 7 - Add Camera Capture Device Input to Capture Session
let captureSession: AVCaptureSession
if let videoCaptureDevice = getBackVideoCaptureDevice() {
if let videoCaptureDeviceInput = getCaptureDeviceInput(captureDevice: videoCaptureDevice) {
if captureSession.canAddInput(videoCaptureDeviceInput) {
captureSession.addInput(videoCaptureDeviceInput)
}
}
}
// Step 8 - Is Torch Available
// Only the back camera has torch
// Torch becomes unavailable when the device overheats
var isTorchAvailable: Bool {
guard let videoCaptureDevice = videoCaptureDevice else { return false }
guard videoCaptureDevice.hasTorch else { return false }
return videoCaptureDevice.isTorchAvailable
}
// Step 9 - Setup Key-Value Observing for Torch Available
// We setup KVO to monitor status of torch available
// When device cools down, torch becomes available
// And torch is unavailable when device overheats
func setupKVOForTorchAvailable() {
guard let videoCaptureDevice = videoCaptureDevice else { return }
guard videoCaptureDevice.hasTorch else { return }
let _ = videoCaptureDevice.observe(\.isTorchAvailable, options: [.new]) { captureDevice, change in
if change.newValue == true {
print("torch is available")
} else {
print("torch is unavailable")
}
}
}
// Step 10 - Turn On/Off Video Camera Torch
func setTorchMode(torchMode: AVCaptureDevice.TorchMode) -> Bool {
guard let videoCaptureDevice = videoCaptureDevice else { return false }
do {
try videoCaptureDevice.lockForConfiguration()
} catch let error as NSError {
print("failed to get lock for configuration on capture device with error \(error)")
}
guard videoCaptureDevice.isTorchAvailable else { return false }
videoCaptureDevice.torchMode = torchMode
videoCaptureDevice.unlockForConfiguration()
return true
}
let status = setTorchMode(torchMode: .on) // turning on torch
let status = setTorchMode(torchMode: .off) // turning off torch
// Step 11 - Remove Video Capture Device Input
captureSession.removeInput(videoCaptureDeviceInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment