iosobjective-cuideviceorientation

iOS get angle of face up orientation


When loading a screen in FaceUp Orientation I need to know the angle of the iPhone.

The iPhone is flat on the table but I just need to know if it is in vertical or horizontal position.

I can't use StatusBarOrientation since I have fixed orientation. The orientation of the status bar is always the same


Solution

  • This may be a good time to use CoreMotion. Looks like reading CoreMotionRate may give you what you want:

    From the docs:

    /*
     *  CMRotationRate
     *  
     *  Discussion:
     *    A structure containing 3-axis rotation rate data.
     *
     *  Fields:
     *    x:
     *      X-axis rotation rate in radians/second. The sign follows the right hand 
     *      rule (i.e. if the right hand is wrapped around the X axis such that the 
     *      tip of the thumb points toward positive X, a positive rotation is one 
     *      toward the tips of the other 4 fingers).
     *    y:
     *      Y-axis rotation rate in radians/second. The sign follows the right hand 
     *      rule (i.e. if the right hand is wrapped around the Y axis such that the 
     *      tip of the thumb points toward positive Y, a positive rotation is one 
     *      toward the tips of the other 4 fingers).
     *      z:
     *          Z-axis rotation rate in radians/second. The sign follows the right hand 
     *      rule (i.e. if the right hand is wrapped around the Z axis such that the 
     *      tip of the thumb points toward positive Z, a positive rotation is one 
     *      toward the tips of the other 4 fingers).
     */
    

    Quick example of how to get these values:

    private lazy var motionManager: CMMotionManager = {
        return CMMotionManager()
    }()
    
    func recordMotion() {
       motionManager.startDeviceMotionUpdatesToQueue(opQueue, withHandler: { (deviceMotion, error) in
                if let motion = deviceMotion {
                     print(motion.rotationRate.x)
                     print(motion.rotationRate.y)
                     print(motion.rotationRate.z)
                }
            })
    }