iOS 调用系统闪光灯

155 阅读1分钟

http://my.oschina.net/CarlHuang/blog/136287

闪光的调用上面链接的文章写得已经很好了.具体的一些实现代码:

.m文件

@interface ViewController () 

@property (nonatomic,strong) AVCaptureSession * captureSession;
@property (nonatomic,strong) AVCaptureDevice * captureDevice;

@property (nonatomic, assign) BOOL isOpen; 

@end


@implementation ViewController 

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isOpen = NO;
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    
    btn.center = self.view.center;
    
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(openFlash) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)openFlash {
    
    if (!self.isOpen) {
        if([self.captureDevice hasTorch] && [self.captureDevice hasFlash])
        {
            if(self.captureDevice.torchMode == AVCaptureTorchModeOff)
            {
                [self.captureSession beginConfiguration];
                [self.captureDevice lockForConfiguration:nil];
                [self.captureDevice setTorchMode:AVCaptureTorchModeOn];
                [self.captureDevice setFlashMode:AVCaptureFlashModeOn];
                [self.captureDevice unlockForConfiguration];
                [self.captureSession commitConfiguration];
            }
        }
        [self.captureSession startRunning];
        self.isOpen = YES;
    } else {
        
        [self.captureSession beginConfiguration];
        [self.captureDevice lockForConfiguration:nil];
        if(self.captureDevice.torchMode == AVCaptureTorchModeOn)
        {
            [self.captureDevice setTorchMode:AVCaptureTorchModeOff];
            [self.captureDevice setFlashMode:AVCaptureFlashModeOff];
        }
        [self.captureDevice unlockForConfiguration];
        [self.captureSession commitConfiguration];
        [self.captureSession stopRunning];
        self.isOpen = NO;
    }
    
    
}

-(AVCaptureSession *)captureSesion
{
    if(_captureSession == nil)
    {
        _captureSession = [[AVCaptureSession alloc] init];
    }
    return _captureSession;
}

-(AVCaptureDevice *)captureDevice
{
    if(_captureDevice == nil)
    {
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _captureDevice;
}