用于检测设备是不是水平的 iOS 代码

Posted

技术标签:

【中文标题】用于检测设备是不是水平的 iOS 代码【英文标题】:iOS code to detect if device is level用于检测设备是否水平的 iOS 代码 【发布时间】:2014-07-14 19:29:44 【问题描述】:

我想编写一个应用程序来检测该人是否持有 iPhone 或 iPad 水平仪,或者他们是否将设备沿 x/y/z 轴的某个位置倾斜以及它的角度。我见过很多提供类似功能的应用程序,但代码不多。

谁能给我指一个在线教程,或者提供演示这些功能的代码?

【问题讨论】:

xcode/apple 文档中的 Motiongraphs 示例代码就是你想要的! @timothykc 我想你的意思是Core Motion? 不。 Coremotion 是框架,但motiongraphs 是一个示例应用程序,可以很好地实时可视化 CoreMotion 数据。他想要示例代码:) 记住你不能在模拟器中运行它——你需要在设备上运行它;) 是的,这正是我想要的!谢谢。您可以将其发布为答案,以便我记下您的回复吗? 【参考方案1】:

Coremotion 是相关的框架。 motiongraphs 是一个很棒的示例应用程序,可以很好地实时可视化 CoreMotion 数据。

【讨论】:

【参考方案2】:

正如@timothykc 所说,MotionGraphs 示例是使用 CoreMotion 库的一个很好的示例。

https://developer.apple.com/library/ios/samplecode/MotionGraphs/Introduction/Intro.html

另一个很好的例子:

http://www.captechconsulting.com/blog/john-morrison/ios-getting-started-accelerometer-data

以下是重点:

1) 使用单例模式访问 CMMotionManager(此 sn-p 直接来自示例项目)。

@interface AppDelegate ()

    CMMotionManager *motionmanager;

@end

@implementation AppDelegate
- (CMMotionManager *)sharedManager

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
        motionmanager = [[CMMotionManager alloc] init];
    );
    return motionmanager;

@end

2) 使用此代码注册对俯仰/滚动/偏航的更新:

CMMotionManager *mManager = [(AppDelegate *)[[UIApplication sharedApplication] delegate] sharedManager];

APLDeviceMotionGraphViewController * __weak weakSelf = self;

if ([mManager isDeviceMotionAvailable] == YES) 
    [mManager setDeviceMotionUpdateInterval:0.1];
    [mManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *deviceMotion, NSError *error)
    
        //Access the pitch, roll, and yaw from the attitude and do something with them.
        //deviceMotion.attitude.yaw
        //deviceMotion.attitude.roll
        //deviceMotion.attitude.pitch
    ];

【讨论】:

以上是关于用于检测设备是不是水平的 iOS 代码的主要内容,如果未能解决你的问题,请参考以下文章

即使 http2 返回代码 200,iOS APNS 也不会在设备上用于开发和生产

用于开发和生产的 iOS 推送通知设备令牌

iOS上是不是有用于频繁位置历史的API?

Xamarin iOS Autolayout:自动调整各种设备的宽度和垂直滚动,同时保持水平滚动禁用演示链接

如何检测 iOS 设备是不是处于静音模式?

iOS 拉动刷新不适用于 iPhone X 等特定设备