我认为您应该使用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.
可能是您正在寻找的。
更新:我知道这不是你最初问的,但我知道通过示例学习通常是最好的,所以这里是使用这个的完整示例(未经测试):
@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];
}
}
这将在您打开开关时开始闪烁,并在您关闭开关后停止。