device_axes
One of the most anticipated features in mobile computing throughout all of history has been the iPhone’s accelerometer.  The ability to receive instantaneous data about the linear acceleration changes of a device along the primary axes in three-dimensional space has been revolutionary.  In particular using this input for iOS game development.  Keep reading and we will answer the question:  How do I access accelerometer data in iOS?

In the early days, starting with iOS 2.0, a shared object UIAccelerometer provides accelerometer data. Simply specify to the UIAccelerometer the interval at which you would like to receive events and set the delegate property.

However, this functionality is deprecated as of iOS 5.0.  Now all the magic happens in the CoreMotion Framework via the CMMotionManager.  This class not only provides accelerometer data but also rotation-rate data, magnetometer data, and other device-motion data such as attitude.  Here we are just going to focus on the accelerometer data.

There are two approaches to getting accelerometer data:  interval based updates and periodic sampling.

Periodic Sampling

Periodic sampling is the preferred method to use for game apps.  This method does not need a block which has more overhead.  With the periodic sampling technique you simply request the accelerometer data when you need it, such as when rendering the frame.

First you need to link to the CoreMotion.framework library and add the proper import statement.

LinkLibrary

Next declare a variable scoped appropriately for when you will need the accelerometer data.

Instantiate the CMMotionManager and call the startAccelerometerUpdates.

Whenever you need the current accelerometer data, retrieve a sampling from the accelerometerData property.

Do not forget to call the stopAccelerometerUpdates when you no longer need the accelerometer data.

Interval Based Updates

Here is a quick look at the alternative method of accessing the accelerometer data.  In this example we set the interval property accelerometerUpdateInterval and then call startAccelerometerUpdatesToQueue:withHandler: providing the block which will execute at the provided interval.

Subscribe to BehindTheCode.Net and stay tuned.  Coming soon we will put this concept to work in a game style tutorial.

Resources

Get information straight from the source with Apple’s CMMotionManager Class Reference