O'Reilly logo

iOS 6 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

18.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 the header file of a view controller that utilizes CMMotionManager to get accelerometer updates:

#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface Retrieving_Accelerometer_DataViewController : UIViewController

@property (nonatomic, strong) CMMotionManager *motionManager;

@end

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

#import "Retrieving_Accelerometer_DataViewController.h"

@implementation Retrieving_Accelerometer_DataViewController

- (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.");
  }

}

- (BOOL)shouldAutorotateToInterfaceOrientation
        :(UIInterfaceOrientation)interfaceOrientation{
  return YES;
}

@end

Discussion

The accelerometer reports three-dimensional data (three axes) that ...

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