首先导入头文件
#import <AVFoundation/AVFoundation.h>
然后
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(20, 40, 200, 40);
button.center = self.view.center;
button.backgroundColor = [UIColor redColor];
[button setTitle:@"打开电筒" forState:UIControlStateNormal];
[button setTitle:@"关闭电筒" forState:UIControlStateSelected];
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
点击事件
-(void)clickButton:(UIButton *)button{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//判断有没有摄像头
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
button.selected = !button.selected;
if (button.selected) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}
}
END.