首先導入
#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;
}
}
就是這麼簡單