打开闪光灯的代码

1.比较常用,也比较简单,因此粘贴到这里

2.调用了AVCaptureSession对象的beginConfiguration方法后,勿忘调用commitConfiguration方法,有始有终.

3.1 在程序①返回时②失去焦点时③扫描成功时千万不要忘记关闭闪光灯,并关闭 session 对象,否则极易崩溃.

 1 - (void)onFlash{
 2     
 3     AVCaptureDevice *avDevice = self.device;
 4     if (![avDevice hasFlash] || ![avDevice hasTorch]) {
 5         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"打开闪光灯失败!请检测您的闪光灯!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
 6         [alert show];
 7         return;
 8     }
 9 
10     [self openFlashLight];
11 }
12 
13 - (void)openFlashLight
14 {
15     UIButton *sender = self.buttonFlash;
16     sender.selected = !sender.selected;
17     if (sender.selected) {
18         [self openFlash];
19     } else{
20         [self shutdownFlash];
21     }
22 }
23 
24 - (void)openFlash{
25     
26     AVCaptureDevice *avDevice = self.device;
27     AVCaptureSession *avSession = self.captureSession;
28     if (avDevice.torchMode == AVCaptureTorchModeOff) {
29         [avSession beginConfiguration];
30         [avDevice lockForConfiguration:nil];
31         [avDevice setTorchMode:AVCaptureTorchModeOn];
32         [avDevice setFlashMode:AVCaptureFlashModeOn];
33         [avDevice unlockForConfiguration];
34         [avSession commitConfiguration];
35         self.buttonFlash.selected = YES;
36     }
37 }
38 
39 - (void)shutdownFlash{
40     
41     AVCaptureDevice *avDevice = self.device;
42     AVCaptureSession *avSession = self.captureSession;
43     if (avDevice.torchMode == AVCaptureTorchModeOn) {
44         [avSession beginConfiguration];
45         [avDevice lockForConfiguration:nil];
46         [avDevice setTorchMode:AVCaptureTorchModeOff];
47         [avDevice setFlashMode:AVCaptureFlashModeOff];
48         [avDevice unlockForConfiguration];
49         [avSession commitConfiguration];
50         self.buttonFlash.selected = NO;
51     }
52 }

3.2以下是退出时的处理代码,不能丢!

 1 - (void)endScan{
 2     [self stopAnimation];
 3     [self shutdownFlash];
 4     [self stopSeesion];
 5 }
 6 
 7 - (void)stopAnimation{
 8     [self.imageViewShockWave.layer removeAllAnimations];
 9 }
10 
11 - (void)shutdownFlash{
12     
13     AVCaptureDevice *avDevice = self.device;
14     AVCaptureSession *avSession = self.captureSession;
15     if (avDevice.torchMode == AVCaptureTorchModeOn) {
16         [avSession beginConfiguration];
17         [avDevice lockForConfiguration:nil];
18         [avDevice setTorchMode:AVCaptureTorchModeOff];
19         [avDevice setFlashMode:AVCaptureFlashModeOff];
20         [avDevice unlockForConfiguration];
21         [avSession commitConfiguration];
22         self.buttonFlash.selected = NO;
23     }
24 }
25 
26 - (void)stopSeesion{
27     if (_captureSession) {
28         [_captureSession stopRunning];
29     }
30 }

 

posted on 2016-04-06 17:44  活最好的自己  阅读(1649)  评论(0编辑  收藏  举报

导航