O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required