如何检查设备上是否存在陀螺仪?

6

想知道如何检查设备(例如iPhone、iPad、iPod等iOS设备)是否具有陀螺仪?

3个回答

13
- (BOOL) isGyroscopeAvailable
{
#ifdef __IPHONE_4_0
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    BOOL gyroAvailable = motionManager.gyroAvailable;
    [motionManager release];
    return gyroAvailable;
#else
    return NO;
#endif

}

参见我的这篇博客文章,了解如何检查iOS设备的不同功能 http://www.makebetterthings.com/blogs/iphone/check-ios-device-capabilities/


在这里使用 #ifdef 有什么优势? - codeperson
1
@jonsibley CMMotionManager 仅适用于 iPhone OS 4,如果我们尝试在早期的操作系统上使用它,它将无法编译。 - Saurabh
3
我认为__IPHONE_4_0只是一个定义的常量。根据这个 StackOverflow 的问题( https://dev59.com/tVHTa4cB1Zd3GeqPPjQE ),似乎正确的做法是使用__IPHONE_OS_VERSION_MIN_REQUIRED >= 40000 - codeperson

3

CoreMotion的运动管理类中内置了一个属性,用于检查硬件可用性。Saurabh的方法需要在发布新设备(iPad 2等)带有陀螺仪时更新您的应用程序。下面是使用苹果文档中记录的检查陀螺仪可用性的属性示例代码:

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

if (motionManager.gyroAvailable)
{
    motionManager.deviceMotionUpdateInterval = 1.0/60.0;
    [motionManager startDeviceMotionUpdates];
}

更多信息请参见文档


1

我认为@Saurabh和@Andrew Theis的答案只是部分正确。

这是一个更完整的解决方案:

- (BOOL) isGyroscopeAvailable
{
// If the iOS Deployment Target is greater than 4.0, then you
// can access the gyroAvailable property of CMMotionManager
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    BOOL gyroAvailable = motionManager.gyroAvailable;
    [motionManager release];
    return gyroAvailable;
// Otherwise, if you are supporting iOS versions < 4.0, you must check the
// the device's iOS version number before accessing gyroAvailable
#else
    // Gyro wasn't available on any devices with iOS < 4.0
    if ( SYSTEM_VERSION_LESS_THAN(@"4.0") )
        return NO;
    else
    {
        CMMotionManager *motionManager = [[CMMotionManager alloc] init];
        BOOL gyroAvailable = motionManager.gyroAvailable;
        [motionManager release];
        return gyroAvailable;
    }
#endif
}

SYSTEM_VERSION_LESS_THAN()这个 StackOverflow 回答 中被定义。


我看了这个页面上所有的答案,完全感到困惑。@jonsibley,"gyroAvailable"方法只在IOS4+中可用,这是真的吗? - ShayanK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接