October 2013
Intermediate to advanced
1053 pages
28h 7m
English
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>@interfaceViewController()@property(nonatomic,strong)CMMotionManager*motionManager;@end@implementationViewController
We will now implement our view controller and take advantage of
the startAccelerometerUpdatesToQueue:withHandler:
method of the CMMotionManager
class:
-(void)viewDidLoad{[superviewDidLoad];self.motionManager=[[CMMotionManageralloc]init];if([self.motionManagerisAccelerometerAvailable]){NSOperationQueue*queue=[[NSOperationQueuealloc]init];[self.motionManagerstartAccelerometerUpdatesToQueue:queuewithHandler:^(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.");}}
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:
typedefstruct{doublex;doubley;doublez;}CMAcceleration;
If you hold your iOS device in front of your face with the screen facing you in ...
Read now
Unlock full access