Reputation: 61463
I need to detect which direction the iPhone is facing so I can record from the non obstructed camera (Front or Back) when dropped.
This will be used in emergency situation and the phone is dropped, or placed in such a way that the active camera is recording nothing of value.
What API or technique can I use to determine this?
Upvotes: 6
Views: 2858
Reputation: 926
Here is a simple function I wrote to start tracking orientation changes so that you can know when it is face down or face up (or whatever orientation you're looking for):
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")
}
})
}
Written in Swift 4 but the API is available since iOS 2.0+
Upvotes: 6
Reputation: 89102
Check the ProximityState property of the UIDevice class. This will tell you if the screen is near an object (the user's face, or flat on the ground).
For newer devices, you can also use CoreMotion. A positive value on the Z-axis should correspond to the phone's screen being facedown.
Upvotes: 2
Reputation: 535118
Use the Core Motion accelerometer. It reports the direction of gravity, which tells you which way the device is facing.
Upvotes: 4