前言
AVCaptureDevice(捕捉设备类)可以完成手机手电筒功能的开发,它属于AVFoundation框架。开发也比较简单,我这里简单地介绍一下。
OC中的代码示例
导入框架
#import <AVFoundation/AVFoundation.h>
定义属性
@property(nonatomic,strong)AVCaptureDevice *device;
@property(nonatomic,assign)BOOL available;
初始化捕捉设备对象
//初始化捕捉设备对象
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
手电筒功能是否可用
//获取是否可用手电筒功能
self.available = self.device.hasTorch;
//提示
if (!self.available) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
打开手电筒
if (self.available) {
[self.device lockForConfiguration:nil];
// AVCaptureTorchModeOn:开 AVCaptureTorchModeOff:关 AVCaptureTorchModeAuto:自动
self.device.torchMode = AVCaptureTorchModeOn;
[self.device unlockForConfiguration];
}
关闭手电筒
if (self.available) {
[self.device lockForConfiguration:nil];
// AVCaptureTorchModeOn:开 AVCaptureTorchModeOff:关 AVCaptureTorchModeAuto:自动
self.device.torchMode = AVCaptureTorchModeOff;
[self.device unlockForConfiguration];
}
Switf中的代码示例(跟OC同理)
导入框架
import AVFoundation
定议成属性并懒加载捕捉设备对象
var isflashlight = false
lazy var device:AVCaptureDevice? = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
手电筒功能是否可用
//MARK: -- 是否支持手电筒功能
func supportFlashlight(){
isflashlight = device?.hasTorch ?? false
if !isflashlight {
let alert = UIAlertView(title: "提示", message: "设备不支持", delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
}
打开或者关闭手电筒
//MARK: -- true:为打开,false:为关闭
func flashlight(_ sure : Bool ) {
if sure {
//打开
do {
try device!.lockForConfiguration()
device!.torchMode = AVCaptureTorchMode.on
device!.unlockForConfiguration()
} catch {
}
}else{
//关闭
do {
try device!.lockForConfiguration()
device!.torchMode = AVCaptureTorchMode.off
device!.unlockForConfiguration()
} catch {
}
}
}
总结
是不是特别简单啊?如果有什么疑问可以Q我:342112780