title: Toggle Flashlight when Motion is detected
body: <p>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!</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>What am i doing wrong</p>
  
  <p>Detecting the shake:</p>
  
  <pre><code>- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
      if (event.type == UIEventSubtypeMotionShake) {
          NSLog(@"shaken, not stirred.");
          [self playSound];
          [self toggleFlashlight];
      }
  }
  </code></pre>
  
  <p>Toggling the Flash ligt:</p>
  
  <pre><code>- (void)toggleFlashlight
  {
      AVCaptureDevice *device =
      [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  
      if ([device hasTorch] &amp;&amp; [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];
          }
      }
      }
  </code></pre>
  
  <p>I would really appreciate your expertise in solving the problem for me!</p>