Alex van Rijs
Alex van Rijs

Reputation: 813

Toggle Flashlight when Motion is detected

I'm currently working on a small project, the meaning of the project/app is that if you were to shake the device the flash ignites. If you shake it again the light turns off!

The first 3/4 toggles between light on or off are working ok, but after 3/4 toggles it is imposible to turn of the light since the device doesnt detect a shake.

Another small problem (since iOS 5.0) is that if a motion is detected the flash will blink very short (1 sec) and than power on. This looks like a short flash.

What am i doing wrong

Detecting the shake:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.type == UIEventSubtypeMotionShake) {
        NSLog(@"shaken, not stirred.");
        [self playSound];
        [self toggleFlashlight];
    }
}

Toggling the Flash ligt:

- (void)toggleFlashlight
{
    AVCaptureDevice *device =
    [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device hasTorch] && [device hasFlash]){

        if (device.torchMode == AVCaptureTorchModeOff) {

            NSLog(@"It's currently off.. turning on now.");

            AVCaptureDeviceInput *flashInput =
            [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];

            AVCaptureVideoDataOutput *output =
            [[AVCaptureVideoDataOutput alloc] init];

            AVCaptureSession *session =
            [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];

            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];

            [session addInput:flashInput];
            [session addOutput:output];

            [device unlockForConfiguration];

            [output release];

            [session commitConfiguration];
            [session startRunning];

            [self setAVSession:session];
            [session release];

        }
        else {
            NSLog(@"It's currently on.. turning off now.");
            [AVSession stopRunning];
        }
    }
    }

I would really appreciate your expertise in solving the problem for me!

Upvotes: 1

Views: 1185

Answers (2)

MatLecu
MatLecu

Reputation: 953

Calling your code in

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

instead of motionEnded might solve your problems.

Upvotes: 1

mackworth
mackworth

Reputation: 5953

Well, I don't know much about it, but it's possible you're starting/stopping the session too quickly (calling ToggleFlashLight too soon after last calling it). You might see this code here... It suggests that you do all that (except for the Torch/FlashModeOn) once to create the session, and then just do the lock/torchModeOn/flashModeOn/unlock to turn on and lock/torchModeOff/flashModeOff/unlock to turn off.

Upvotes: 2

Related Questions