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.5. Retrieving Gyroscope Data

Problem

You want to be able to retrieve information about the device’s motion from the gyroscope hardware on an iOS device.

Solution

Follow these steps:

  1. Find out whether the gyroscope hardware is available on the iOS device. Please refer to Recipe 21.2 for directions on how to do this.

  2. If the gyroscope hardware is available, make sure it is not already sending you updates. Please refer to Recipe 21.2 for directions.

  3. Use the setGyroUpdateInterval: instance method of CMMotionManager to set the number of updates you want to receive per second. For instance, for 20 updates per second (one second), set this value to 1.0/20.0.

  4. Invoke the startGyroUpdatesToQueue:withHandler: instance method of CMMotionManager. The queue object could simply be the main operation queue (as we will see later), and the handler block must follow the CMGyroHandler format.

The following code implements these steps:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    CMMotionManager *manager = [[CMMotionManager alloc] init];
    
    if ([manager isGyroAvailable]){
        
        if ([manager isGyroActive] == NO){
            
            [manager setGyroUpdateInterval:1.0f / 40.0f];
            
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            
            [manager
             startGyroUpdatesToQueue:queue
             withHandler:^(CMGyroData *gyroData, NSError *error) {
                 
                 NSLog(@"Gyro Rotation x = %.04f", gyroData.rotationRate.x);
                 NSLog(@"Gyro Rotation y = %.04f", gyroData.rotationRate.y);
                 NSLog(@"Gyro Rotation z = %.04f" ...

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