Search code examples
iosobjective-cios6cameraaccelerometer

Switch between front and back camera determined by accelerometer


I am trying to switch between front and back camera in Objective-C by using UIAccelerometer. Essentially, if the device is face up, I want the back camera to be on. If the device is face down (screen is down), I would like the front camera to be active instead. What is the best way to tackle this problem? I am accessing the camera via AVFoundation. Thanks!


Solution

  • I have some code that might help you, created in one project of mine that uses the camera too.

    This is the code of the accelerometer's delegate, where you can keep track of the device's position.

    - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration;
    {
       CGFloat x = -[acceleration x];
       CGFloat y = [acceleration y];
       CGFloat angle = atan2(y, x);
    
       if ( angle >= -2.25f && angle <= -0.25f )
       {
            self.interfaceOrientation = UIInterfaceOrientationPortrait;
       }
       else if ( angle >= -1.75f && angle <= 0.75f )
       {
            self.interfaceOrientation = UIInterfaceOrientationLandscapeRight;
       }
       else if( angle >= 0.75f && angle <= 2.25f )
       {
            self.interfaceOrientation = UIInterfaceOrientationPortraitUpsideDown;
       }
       else if ( angle <= -2.25f || angle >= 2.25f )
       {
            self.interfaceOrientation = UIInterfaceOrientationLandscapeLeft;
       }
    }
    

    To see with more details, how to use the delegate, how to user declare things, etc check the code on my github:

    Implementation file: https://github.com/lucasecf/flipped-cam/blob/master/flipped-cam/LEImagePickerController.m

    Project page: https://github.com/lucasecf/flipped-cam