iOS device orientation disregarding orientation lock

后端 未结 10 1277
天涯浪人
天涯浪人 2020-11-29 01:59

I want to query the orientation the iPhone is currently in. Using

[UIDevice currentDevice].orientation

works as long as the device isn\'t

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 02:44

    Using Satachito's great answer here is code which will also detect if the device is face up or face down

    import CoreMotion
    

    var mm: CMMotionManager!
    
    init() {
        self.mm = CMMotionManager()
        self.mm.accelerometerUpdateInterval = 0.2
    }
    
    public func startOrientationUpdates() {
        //  Using main queue is not recommended. So create new operation queue and pass it to startAccelerometerUpdatesToQueue.
        //  Dispatch U/I code to main thread using dispach_async in the handler.
        self.mm.startAccelerometerUpdates( to: OperationQueue() ) { p, _ in
            if let p = p {
                if(p.acceleration.x > -0.3 && p.acceleration.x < 0.3 && p.acceleration.z < -0.95) {
                    print("face up")
                }
                else if(p.acceleration.x > -0.3 && p.acceleration.x < 0.3 && p.acceleration.z > 0.95) {
                    print("face down")
                }
                else {
                    print(
                        abs( p.acceleration.y ) < abs( p.acceleration.x )
                            ?   p.acceleration.x > 0 ? "Right"  :   "Left"
                            :   p.acceleration.y > 0 ? "Down"   :   "Up"
                    )
                }
    
            }
        }
    }
    
    public func endOrientationUpdates() {
        self.mm.stopAccelerometerUpdates()
    }
    

提交回复
热议问题