How to turn flashlight ON and OFF in swift?
Update #1: (torchActive
isn't returning the expected value; perhaps because it's been modified)
Update #2: For Swift 2.0
To toggle the flash from on to off (not just "on" as in mad pig's answer), you can use the following method:
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)
}
}
}
I used nested do-catch blocks to implement Awesomeness's suggestion from the comments. This way, even if try device.setTorchModeOnWithLevel(1.0)
fails, the device is properly unlocked for configuration.
Update #3: For Swift 4:
(I edited the code a bit to my personal taste)
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)
}
}
Original answer:
To toggle the flash from on to off (not just "on" as in mad pig's answer), you can use the following method:
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()
}
}
Can not get the Flashlight to turn ON or OFF in my app - Swift
Yeah, you are just defining a function inside an @ibaction function but you never call it. What you can do is define your function outside of the @ibaction and call it when the button is pressed :
import AVFoundation
func toggleFlash(on: Bool) {
guard let device = AVCaptureDevice.default(for: .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")
}
}
@IBAction func toggleFlash(_ sender: UIButton) {
toggleFlash(on: true)
//If you want to set it off just call toggleFlash(on : Falsse)
}
Changing iPhone flashlight intensity over time (Swift)
Use the function setTorchModeOnWithLevel to set the level, you can use a timer to set times when the level will change.
Here's an example of how to do this (implemented in the AppDelegate of a brand-new iOS Single View Application):
var timer: NSTimer?
func applicationDidBecomeActive(application: UIApplication) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "delayedAction", userInfo: nil, repeats: true)
}
let maxLightLevel = 5
var lightLevel = 5
func delayedAction() {
guard let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
else {
timer?.invalidate()
return
}
if let _ = try? device.lockForConfiguration() {
defer { device.unlockForConfiguration() }
if lightLevel == 0 {
timer?.invalidate()
device.torchMode = .Off
}
else {
try! device.setTorchModeOnWithLevel(Float(lightLevel)/Float(maxLightLevel))
}
--lightLevel
}
}
This code is just a rough example and should have appropriate behaviors added to handle switching apps, thrown exceptions, and so on.
Keep torch on while taking video iOS swift
Call this method
Inside your camera active/Open func
or When device camera active -
func flashActive() {
if let currentDevice = AVCaptureDevice.default(for: AVMediaType.video), currentDevice.hasTorch {
do {
try currentDevice.lockForConfiguration()
let torchOn = !currentDevice.isTorchActive
try currentDevice.setTorchModeOn(level:1.0)//Or whatever you want
currentDevice.torchMode = torchOn ? .on : .off
currentDevice.unlockForConfiguration()
} catch {
print("error")
}
}
}
How to turn the iPhone camera flash on/off swift 2?
@IBAction func didTouchFlashButton(sender: UIButton) {
let avDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
// check if the device has torch
if avDevice.hasTorch {
// lock your device for configuration
do {
let abv = try avDevice.lockForConfiguration()
} catch {
print("aaaa")
}
// check if your torchMode is on or off. If on turns it off otherwise turns it on
if avDevice.torchActive {
avDevice.torchMode = AVCaptureTorchMode.Off
} else {
// sets the torch intensity to 100%
do {
let abv = try avDevice.setTorchModeOnWithLevel(1.0)
} catch {
print("bbb")
}
// avDevice.setTorchModeOnWithLevel(1.0, error: nil)
}
// unlock your device
avDevice.unlockForConfiguration()
}
}
How to turn on/offf camera flash light with ARKit?
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 // set on
} else {
device.torchMode = .off // set off
}
device.unlockForConfiguration()
} catch {
print("Torch could not be used")
}
} else {
print("Torch is not available")
}
}
Call this as
toggleTorch(on: true) of toggleTorch(on: false)
ref: Hacking with Swift
Related Topics
Objective C - Pass by Value and Pass by Reference
How to Import Private Framework Headers in a Swift Framework
Uitextfield Only Top and Bottom Border
iOS 9 Ats Ssl Error with Supporting Server
Avplayer Stalling on Large Video Files Using Resource Loader Delegate
How to Know All My Tasks in Grand Central Dispatch Finished
How to Transfer Files from One Application to Another in the Same iOS Device
Safeareainsets in Uiview Is 0 on an iPhone X
Swift Read Userinfo of Remote Notification
Filenames Are Used to Distinguish Private Declarations of the Same Name' Error
Callback Function Syntax in Swift
Where Does the Indexpath of Dequeuereusablecellwithidentifier:Forindexpath: Get Used
Memory-Mapped Files and Low-Memory Scenarios
How to Set Multi Line Large Title in Navigation Bar? ( New Feature of iOS 11)
Code Sign Error on Xcode 8 and iOS 10 Cordova Project
Uiscrollview's Origin Changes After Popping Back to the Uiviewcontroller