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 ...
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.