iOS Gyroscope API

use*_*765 13 iphone objective-c ipad ios gyroscope

我正在学习使用iOS中的陀螺仪传感器编写应用程序.对于加速度计,是否存在类似于UIAcceleration/UIAccelerometer/UIAccelerometerDelegate的陀螺仪处理类?

Sri*_*aju 31

第一个进口CoreMotion框架

#import <CoreMotion/CoreMotion.h>

    self.motionManager = [[CMMotionManager alloc] init];


    //Gyroscope
    if([self.motionManager isGyroAvailable])
    {
        /* Start the gyroscope if it is not active already */ 
        if([self.motionManager isGyroActive] == NO)
        {
            /* Update us 2 times a second */
            [self.motionManager setGyroUpdateInterval:1.0f / 2.0f];

            /* Add on a handler block object */

            /* Receive the gyroscope data on this block */
            [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue]
             withHandler:^(CMGyroData *gyroData, NSError *error)
            {
                NSString *x = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.x];
                self.gyro_xaxis.text = x;

                NSString *y = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.y];
                self.gyro_yaxis.text = y;

                NSString *z = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.z];
                self.gyro_zaxis.text = z;
            }];
        }
    }
    else
    {
        NSLog(@"Gyroscope not Available!");
    }
Run Code Online (Sandbox Code Playgroud)

正如代码所说,首先我创建了一个运动管理器的实例.然后我看看该设备是否支持陀螺仪.如果没有优雅地死,否则设置陀螺仪更新间隔然后注册以从陀螺仪获得更新.通过这些更新,您需要定义您想要对值执行的操作的自定义逻辑.那就是你很高兴...

  • [self.motionManager isGyroAvailable]这是必须的吗?如果陀螺仪不可用会怎么样?应用程序崩溃了吗?或者返回空值.如果它返回null值,那么哪个对象将返回null? (2认同)
  • 它是一个检查,因为较旧的iPhone没有陀螺仪.如果您在设备本身不支持时开始使用陀螺仪API,它可能会崩溃.更安全而不是抱歉...... (2认同)

Car*_*len 6

对于陀螺仪数据,您需要使用CoreMotion.通过阅读iOS事件处理指南相关部分开始.您需要使用两个类:CMGyroData(用于封装陀螺仪事件数据)和CMMotionManager(用于注册陀螺仪事件).

更多信息可以在这个问题的选定答案中找到:Apple陀螺仪示例代码