Search code examples
iosswiftcore-motion

Get current iOS device orientation even if device's orientation locked


I want to get the current iOS device orientation even if device's orientation is locked. (Just like iOS Camera app)

I want to detect Portrait, Landscape Left and Landscape Right at least.

UIDeviceOrientation and UIInterfaceOrientation do not seem to work when orientation is locked.

In this case, I think that we will use CoreMotion.

How do i logic it in swift4?


Solution

  • Declare motion manager with Core Motion

        var orientationLast = UIInterfaceOrientation(rawValue: 0)!
        var motionManager: CMMotionManager?
    

    Motion manager initialization

    and call this function in viewDidLoad

        func initializeMotionManager() {
         motionManager = CMMotionManager()
         motionManager?.accelerometerUpdateInterval = 0.2
         motionManager?.gyroUpdateInterval = 0.2
         motionManager?.startAccelerometerUpdates(to: (OperationQueue.current)!, withHandler: {
            (accelerometerData, error) -> Void in
            if error == nil {
                self.outputAccelerationData((accelerometerData?.acceleration)!)
            }
            else {
                print("\(error!)")
            }
            })
         }   
    

    To analyze accelerometer data

     func outputAccelerationData(_ acceleration: CMAcceleration) {
        var orientationNew: UIInterfaceOrientation
        if acceleration.x >= 0.75 {
            orientationNew = .landscapeLeft
            print("landscapeLeft")
        }
        else if acceleration.x <= -0.75 {
            orientationNew = .landscapeRight
            print("landscapeRight")
        }
        else if acceleration.y <= -0.75 {
            orientationNew = .portrait
            print("portrait")
            
        }
        else if acceleration.y >= 0.75 {
            orientationNew = .portraitUpsideDown
            print("portraitUpsideDown")
        }
        else {
            // Consider same as last time
            return
        }
        
        if orientationNew == orientationLast {
            return
        }
        orientationLast = orientationNew
    }