Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Ryan Burgess

macrumors 6502
Original poster
Jan 26, 2013
320
48
Hi, I have an app that I want to make a flashlight out of. Basically I want to have a button in the middle of the screen, that when held (for a second or two) will toggle the LED on the phone. Either that, or pushing the button 3 times fast will toggle the LED.

Which of these would be easiest to code, and how would I code it? I have literally no idea how to go about this so any help is appreciated.

EDIT

I have this much code right now and It is working, sort of...

Code:
- (IBAction)buttonClicked:(id)sender {
    UIButton *button = (UIButton *)sender;
    if (!_onOff) {
        AVCaptureSession * session = [[AVCaptureSession alloc] init];
        
        [session beginConfiguration];
        
        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
            [device unlockForConfiguration];
            
            AVCaptureDeviceInput * flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
            if (flashInput){
                [session addInput:flashInput];
            }
            AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc] init];
            [session addOutput:output];
            [session commitConfiguration];  
            [session startRunning];
        }
        [button setTitle:@"Off" forState:UIControlStateNormal];
    }
    else {
        [self.view setBackgroundColor:[UIColor blackColor]];
        [button setTitle:@"On" forState:UIControlStateNormal];
    }

My only problem is that the LED on the flash on the phone only turns on for a second, then it turns off, regardless of whether I push the off button or not. What am i missing here that enables me to leave the LED on until the off button is pressed?

Thanks
 
Last edited:
Though I have never used the torch,
what happens if you remove this:
Code:
[device setFlashMode:AVCaptureFlashModeOn];

also found this...
Code:
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOn];  // use AVCaptureTorchModeOff to turn off
    [device unlockForConfiguration];
}
 
You can also use the touch and hold gesture recognizer for that event or the tap gesture requiring 3 taps. Its only a few lines of code for each of those.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.