还是那句很欠揍的话,没啥难度,直接上代码。
//
// ViewController.m
// Demo—闪光灯
//
// Created by yyt on 16/4/21.
// Copyright © 2016年 yyt. All rights reserved.
//
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *lightButton = [UIButton buttonWithType:UIButtonTypeCustom];
lightButton.frame = CGRectMake(20, 160, self.view.bounds.size.width-40, 40);
lightButton.backgroundColor = [UIColor orangeColor];
[lightButton setTitle:@"open" forState:UIControlStateNormal];
[lightButton setTitle:@"close" forState:UIControlStateSelected];
[lightButton addTarget:self action:@selector(clickLightButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:lightButton];
}
- (void)clickLightButton:(UIButton *)sender {
NSLog(@"闪光灯");
sender.selected = !sender.selected;
if (sender.selected) {
[self turnTorchOn:YES];
}
else{
[self turnTorchOn:NO];
}
}
- (void)turnTorchOn:(BOOL)on
{
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}
}
}
@end