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.2. Detecting the Availability of a Gyroscope

Problem

You want to find out whether the current iOS device that is running your program has gyroscope hardware available.

Solution

Use the isGyroAvailable method of an instance of CMMotionManager to detect the gyroscope hardware. The isGyroActive method is also available if you want to detect whether the gyroscope hardware is currently sending updates to your program (in other words, whether it is active):

#import "AppDelegate.h"
#import <CoreMotion/CoreMotion.h>

@implementation AppDelegate

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    
    if ([motionManager isGyroAvailable]){
        NSLog(@"Gryro is available.");
    } else {
        NSLog(@"Gyro is not available.");
    }
    
    if ([motionManager isGyroActive]){
        NSLog(@"Gryo is active.");
    } else {
        NSLog(@"Gryo is not active.");
    }
    
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

iOS Simulator does not have gyroscope simulation in place. If you run this code on the simulator, you will receive results similar to these in the console window:

Gyro is not available.
Gyro is not active.

If you run this code on an iOS device with a gyroscope, such as the new iPhone, the results could be different:

Gyro is available.
Gyro is not active.

Discussion

If you plan to release an application ...

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