对于我的iOS应用程序,我想实现一个功能,当设备面朝下时屏幕应关闭(如接听电话时).所以我开始检测设备方向:
//in my ViewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.rotated(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil)
//called when the device changes orientation
func rotated(notification: NSNotification){
if UIDevice.currentDevice().orientation == UIDeviceOrientation.FaceDown{
print("device = faced down")
}else{
print("device != faced down")
}
}
Run Code Online (Sandbox Code Playgroud)
当设备停机时,我已经打电话了
UIDevice.currentDevice().proximityMonitoringEnabled = true
Run Code Online (Sandbox Code Playgroud)
其他
UIDevice.currentDevice().proximityMonitoringEnabled = false
Run Code Online (Sandbox Code Playgroud)
这个问题UIDeviceOrientationDidChangeNotification似乎有点迟了所以当rotated()调用该功能时,设备已经面朝下了,事实证明,为了 proximityMonitoringEnabled = true关闭屏幕,接近传感器不应该已经被覆盖了!我很确定这是Apple的限制,但也许有人确实找到了解决方案或遇到了解决方法!提前致谢.
方法:
由于 iOS 在更改方向之前不提供,因此我们不能依赖“ UIDeviceOrientationDidChangeNotification ”。相反,我们可以使用 CoreMotion Framework 并访问硬件的陀螺仪来检测可能的 FaceDown 方向并适当设置 approximationMonitoringEnabled。
陀螺仪数据:
使用陀螺仪观察低于值可能会检测面朝下方向。
let gyroData = (minX:-3.78, minY:-3.38, minZ:-5.33, maxX:3.29, maxY:4.94, maxZ:3.36)
Run Code Online (Sandbox Code Playgroud)
斯威夫特的解决方案:
class ProximityViewController: UIViewController {
let cmManager = CMMotionManager(), gyroData = (minX:-3.78, minY:-3.38, minZ:-5.33, maxX:3.29, maxY:4.94, maxZ:3.36)
override func viewDidLoad() {
super.viewDidLoad()
//Using GyroMotion
experimentCoreMotion()
}
//MARK: - Using Core Motion
func experimentCoreMotion() {
if cmManager.gyroAvailable {
//Enable device orientation notification
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
cmManager.gyroUpdateInterval = 0.1
handleFaceDownOrientation()
}
}
func handleFaceDownOrientation() {
cmManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: { (data:CMGyroData?, error: NSError?) in
if self.isGyroDataInRange(data!) {
UIDevice.currentDevice().proximityMonitoringEnabled = (UIDevice.currentDevice().orientation == .FaceDown)
if UIDevice.currentDevice().orientation == .FaceDown { print("FaceDown detected") }
else { print("Orientation is not facedown") }
}
})
}
func isGyroDataInRange(val: CMGyroData) -> Bool {
return ((val.rotationRate.x > gyroData.minX && val.rotationRate.x < gyroData.maxX) &&
(val.rotationRate.y > gyroData.minY && val.rotationRate.y < gyroData.maxY) &&
(val.rotationRate.z > gyroData.minZ && val.rotationRate.z < gyroData.maxZ))
}
}
Run Code Online (Sandbox Code Playgroud)
希望我的解决方案能够解决您的疑问。让我知道该解决方案可以很好地满足您的要求。
陀螺仪和加速度计观测:
我已经使用陀螺仪和加速度计实验了 FaceDown 方向的可能值。IMO,陀螺仪数据似乎不错,但可以探索其他硬件的传感器来检测面朝下方向。