O'Reilly logo

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

16.1. Detecting the Availability of an Accelerometer

Problem

In your program, you want to detect whether the accelerometer hardware is available.

Solution

Use the isAccelerometerAvailable method of CMMotionManager to detect the accelerometer hardware. The isAccelerometerActive method can also be used to detect whether the accelerometer hardware is currently sending updates to the program.

Let’s first make sure we have imported the required header files:

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

@interface Detecting_the_Availability_of_an_AccelerometerAppDelegate
           : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

Next, go on to detect the availability of accelerometer in the implementation file of our app delegate:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  CMMotionManager *motionManager = [[CMMotionManager alloc] init];

  if ([motionManager isAccelerometerAvailable]){
    NSLog(@"Accelerometer is available.");
  } else{
    NSLog(@"Accelerometer is not available.");
  }

  if ([motionManager isAccelerometerActive]){
    NSLog(@"Accelerometer is active.");
  } else {
    NSLog(@"Accelerometer is not active.");
  }

  self.window = [[UIWindow alloc] initWithFrame:
                 [[UIScreen mainScreen] bounds]];

  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
  return YES;
}

Accelerometer hardware might be available on the iOS device running your program. This, however, does not ...

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