Sunday, December 19, 2010

iPhone face up/face down: Quick and Dirty UIAccelerometer

One thing I love about smartphones is all the little trinkets built into the device... even something as trivial as detecting if the device is "face up" or "face down".

For the iPhone, the natural way to detect the device orientation is to use the "UIDeviceOrientation" class... like so:



This is great, but I found that this method wasn't always giving me exactly what I wanted. I needed a way to detect the exact moment in time when the user flipped the phone, but it didn't seem to work as I had planned.

Instead, I found a just-as-simple way to detect the phone being face up/face down using the UIAccelerometer class. You need to do three things:

First, tell your view controller you will be using the delegate




Next, write your UIAccelerometer delegate.




If you play around with the accelerometer, you'll see that the "z" coordinate is around -1.0 when the device is face up, and around 1.0 when the device is face down (and somewhere in between as the device is being moved). I'm going to assume the device is "face up" when the z value is less than 0, otherwise I will assume it is "face down".

Finally, set up the UIAccelerometer and tell it to use your delegate:



You can get the source here.

No comments:

Post a Comment