打开手电筒照明的思路:初始化相机设备 -> 点击按钮 -> 改变照明状态 -> 根据状态打开或关闭手电筒
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong) AVCaptureDevice *device;//捕获设备
@end
@implementation ViewController
{
BOOL device_open;//判断照明状态
UIButton *scanBtn;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建按钮
[self creatControl];
}
- (void)creatControl {
//初始化相机设备
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//照明按钮
scanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
scanBtn.frame = CGRectMake(100, 100, 100, 44);
[scanBtn setTitle:@"打开照明" forState:UIControlStateNormal];
[scanBtn addTarget:self action:@selector(scanBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:scanBtn];
}
-(void)scanBtnOnClick {
NSLog(@"%@",device_open?@"YES":@"NO");
//改变状态
device_open = !device_open;
//判断设备是否有闪关灯
if (![self.device hasTorch]) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
message:@"当前设备没有闪关灯,无法开启照明功能"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:sureAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self.device lockForConfiguration:nil];
//根据状态,打开或关闭照明
if (device_open) {
[self.device setTorchMode:AVCaptureTorchModeOn];
[scanBtn setTitle:@"关闭照明" forState:UIControlStateNormal];
}
else {
[self.device setTorchMode:AVCaptureTorchModeOff];
[scanBtn setTitle:@"打开照明" forState:UIControlStateNormal];
}
}
@end