如何判断iPhone是否面朝下"或者"面朝上"?

时间:2016-03-19 02:39:43

标签: ios iphone xamarin

我需要检测iPhone面向哪个方向,以便我可以在拍摄时从无遮挡的相机(正面或背面)进行录制。

这将在紧急情况下使用,手机掉落或放置的方式使有源相机无法记录任何有价物品。

我可以使用哪种API或技术来确定这一点?

3 个答案:

答案 0 :(得分:4)

使用Core Motion加速度计。它会报告重力方向,它会告诉您设备面向哪个方向。

答案 1 :(得分:2)

检查UIDevice类的ProximityState属性。这将告诉您屏幕是否靠近物体(用户的脸部,或平坦的地面)。

对于较新的设备,您还可以使用CoreMotion。 Z轴上的正值应对应于手机屏幕正面朝下。

答案 2 :(得分:2)

这是我编写的一个简单函数,用于开始跟踪方向更改,以便您可以知道它何时面朝下或面朝上(或者您正在寻找的任何方向):

func trackOrientationChanges() {
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil, using:  
    { notificiation in
        if UIDevice.current.orientation == .faceDown {
            print("Device is face down")
        } else {
            print("Device is not face down")
        }
    })
}

使用Swift 4编写,但API自iOS 2.0 +

起可用