21.3. Retrieving Accelerometer Data

Problem

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

Solution

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;
@end

@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];
        [self.motionManager
         startAccelerometerUpdatesToQueue:queue
         withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
             NSLog(@"X = %.04f, Y = %.04f, Z = %.04f",
                   accelerometerData.acceleration.x,
                   accelerometerData.acceleration.y,
                   accelerometerData.acceleration.z);
         }];
    } else {
        NSLog(@"Accelerometer is not available.");
    }
    
}

Discussion

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.