Skip to content

Flashlight

The device's torch (LED flash) can be useful for various features, such as providing a flashlight function, signaling notifications, or enhancing low-light camera modes. By integrating torch control, your app can turn the flashlight on or off directly from JavaScript.

Implementation

  1. Create a Swift File
    • In Xcode, go to File > New > File From Template...
    • Select Swift File, name it FlashlightController.swift, and paste the following code:
swift
import AVFoundation
import Foundation

class FlashlightController {
    private var device: AVCaptureDevice?

    init() {
        guard let device = AVCaptureDevice.default(for: .video) else {
           print("Failed to get the camera device")
           return
       }

        self.device = device

        if device.hasTorch {
            print("Device has torch capability")
        } else {
            print("Device does not have torch capability")
        }
    }

    func turnOnFlashlight() {
        guard let device = device, device.hasTorch else { return }

        do {
            try device.lockForConfiguration()
            try device.setTorchModeOn(level: 1.0)
            device.unlockForConfiguration()
        } catch {
            print("Error turning on flashlight: \(error.localizedDescription)")
        }
    }

    func turnOffFlashlight() {
        guard let device = device, device.hasTorch else { return }

        do {
            try device.lockForConfiguration()
            device.torchMode = .off
            device.unlockForConfiguration()
        } catch {
            print("Error turning off flashlight: \(error.localizedDescription)")
        }
    }
}
  1. Integrate with Your View Controller
    • In MainViewController.swift, add methods to interact with the FlashlightController class and expose them to JavaScript:
swift
// Function to turn on LED flashlight
@objc func turnOnFlashlight(_ params: [String: String]) {
    flashlightController.turnOnFlashlight()
}

// Function to turn off LED flashlight
@objc func turnOffFlashlight(_ params: [String: String]) {
    flashlightController.turnOffFlashlight()
}
  1. Using the Flashlight in JavaScript
    • To control the flashlight from JavaScript simply call native turnOnFlashlight and turnOffFlashlight methods:
javascript
// This will turn on the flashlight
enClose({
    nativeCall: 'turnOnFlashlight',
});

// This will turn off the flashlight
enClose({
    nativeCall: 'turnOffFlashlight',
});