21.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 "AppDelegate.h"#import <CoreMotion/CoreMotion.h>@implementationAppDelegate
Next, go on to detect the availability of an accelerometer in the implementation file of our app delegate:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{CMMotionManager*motionManager=[[CMMotionManageralloc]init];if([motionManagerisAccelerometerAvailable]){NSLog(@"Accelerometer is available.");}else{NSLog(@"Accelerometer is not available.");}if([motionManagerisAccelerometerActive]){NSLog(@"Accelerometer is active.");}else{NSLog(@"Accelerometer is not active.");}self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];self.window.backgroundColor=[UIColorwhiteColor];[self.windowmakeKeyAndVisible];returnYES;}
Accelerometer hardware might be available on the iOS device running your program. This, however, does not mean the accelerometer hardware is sending updates to your program. If the accelerometer or gyroscope is sending updates to your ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access