所以我试图创建一个LED频闪灯,我已经设法为灯打开/关闭开关。这是我的代码:
@implementation ViewController
- (void) setTorchOn:(BOOL)isOn
{
AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:isOn ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];
}
-(IBAction)changedSate:(id)sender {
UISwitch *switchValue = (UISwitch*)sender;
[self setTorchOn:[switchValue isOn]];
我想知道是否有人可以帮我解决这个问题。
答案 0 :(得分:0)
只需做一个循环,持续打开和关闭火炬。循环的类型取决于您希望如何实现它。
答案 1 :(得分:0)
我认为你应该使用NSTimer课来反复切换火炬。还有其他方法,但只需使用sleep()调用不循环。
// Have an NSTimer* timer and BOOL torchOn and volatile BOOL stopStrobe property in your class...
- (void) startFlashing{
self.timer = [[NSTimer alloc] initWithFireDate:[NSDate timeInvervalSinceNow: 0] interval:0.1 target:self selector:@selector(toggleTorch) userInfo:nil repeats:YES];
}
- (void) toggleTorch{
if (stopStrobe){
[self.timer invalidate];
}
torchOn = !torchOn
[self setTorchOn:torchOn];
}
// Set stopStrobe to YES elsewhere in your program when you want it to stop.
可能是您正在寻找的。 p>
更新:我知道这不是你最初提出的问题,但我知道通常最好通过示例来学习,所以这里是使用这个(未经测试)的完整示例:
@interface ViewController()
@property(nonatomic) BOOL torchOn;
@property(atomic) BOOL stopStrobe;
@end
@implementation ViewController
- (id) init{
self = [super init];
if (self){
self.torchOn = NO;
self.stopStrobe = NO;
}
}
- (void) setTorchOn:(BOOL)isOn
{
AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:isOn ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];
}
- (void) toggleTorch{
if (stopStrobe){
[self.timer invalidate];
}
self.torchOn = !self.torchOn
[self setTorchOn:self.torchOn];
}
- (void) startFlashing{
self.timer = [[NSTimer alloc] initWithFireDate:[NSDate timeInvervalSinceNow: 0] interval:0.1 target:self selector:@selector(toggleTorch) userInfo:nil repeats:YES];
}
-(IBAction)changedSate:(id)sender {
UISwitch *switchValue = (UISwitch*)sender;
if ([switchValue isOn]{
self.stopStrobe = NO;
[self startFlashing];
}
else{
[self.stopStrobe = YES];
}
}
无论何时打开开关都会开始闪烁,一旦关闭开关就会停止闪烁。