21.3. Retrieving Accelerometer Data


You want to ask iOS to send accelerometer data to your application.


Use the startAccelerometerUpdatesToQueue:withHandler: instance method of CMMotionManager. Here is our view controller that utilizes CMMotionManager to get accelerometer updates:

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()
@property (nonatomic, strong) CMMotionManager *motionManager;

@implementation ViewController

We will now implement our view controller and take advantage of the startAccelerometerUpdatesToQueue:withHandler: method of the CMMotionManager class:

- (void)viewDidLoad{
    [super viewDidLoad];
    self.motionManager = [[CMMotionManager alloc] init];
    if ([self.motionManager isAccelerometerAvailable]){
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
         withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
             NSLog(@"X = %.04f, Y = %.04f, Z = %.04f",
    } else {
        NSLog(@"Accelerometer is not available.");


The accelerometer reports three-dimensional data (three axes) that iOS reports to your program as x, y, and z values. These values are encapsulated in a CMAcceleration structure:

typedef struct {
	double x;
	double y;
	double z;
} CMAcceleration;

If you hold your iOS device in front of your face with the screen facing you in ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.