天天看点

IOS 之 使用闪光灯当手电筒

首先导入

#import <AVFoundation/AVFoundation.h> 头文件和引入AVFoundation库文件

头文件声明变量

@interface UTTorchViewController : UIViewController

@property (strong, nonatomic) AVCaptureDevice *device;
@property (assign, nonatomic) BOOL isLighOn;
@property (strong, nonatomic) UIButton *btn;


- (void)press:(id)pSender;

@end
           

代码文件如下

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 300, 300)];
    [_btn setBackgroundImage:[UIImage imageNamed:@"torch_off"] forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(press:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
    
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ( ![_device hasTorch] )
    {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备没有闪光灯,不支持手电筒功能!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
    }
    
    [self setIsLighOn:NO];
    // Do any additional setup after loading the view from its nib.
}


#pragma mark - Custom method
- (void)press:(id)pSender
{
    if ( _isLighOn )
    {
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device unlockForConfiguration];
        [_btn setBackgroundImage:[UIImage imageNamed:@"torch_off"] forState:UIControlStateNormal];
        _isLighOn = NO;
    }else
    {
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device unlockForConfiguration];
        [_btn setBackgroundImage:[UIImage imageNamed:@"torch_on"] forState:UIControlStateNormal];
        _isLighOn = YES;
    }
}
           

就是这么简单