#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic,assign) BOOL lightOn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//hasTorch :返回YES表名手机上有手电筒
if (![_device hasTorch]) {
NSLog(@"手电筒坏了");
return;
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
_lightOn = !_lightOn;
//根据ligthOn状态判断打开还是关闭
if (_lightOn) {
// 请求独占访问硬件设备
[_device lockForConfiguration:nil];
// 开启手电筒
[_device setTorchMode:AVCaptureTorchModeOn];
// 解除独占访问硬件设备
[_device unlockForConfiguration];
}else{
//关闭手电筒
[_device lockForConfiguration:nil];
[_device setTorchMode:AVCaptureTorchModeOff];
[_device unlockForConfiguration];
}
}
网友评论