在一个维度上确定设备方向及其结果angular度?

我有以下设置:

在这里输入图像说明

一个iPhone躺在桌子上的天花板上(alpha = 0度)。 当iPhone向上移动,如上图所示,αangular增加。

如何计算alphaangular度的值,而不需要考虑任何可能改变的轴。 我只对这一个轴感兴趣。

从桌子上抬起时,我如何得到正确的alphaangular度? 如何在alpha值发生变化时得到通知?

您可以使用CMMotionManager类来监视设备运动更改。

目标C

 // Ensure to keep a strong reference to the motion manager otherwise you won't get updates self.motionManager = [[CMMotionManager alloc] init]; if (self.motionManager.deviceMotionAvailable) { self.motionManager.deviceMotionUpdateInterval = 0.1; // For use in the montionManager's handler to prevent strong reference cycle __weak typeof(self) weakSelf = self; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [self.motionManager startDeviceMotionUpdatesToQueue:queue withHandler:^(CMDeviceMotion *motion, NSError *error) { // Get the attitude of the device CMAttitude *attitude = motion.attitude; // Get the pitch (in radians) and convert to degrees. NSLog(@"%f", attitude.pitch * 180.0/M_PI); dispatch_async(dispatch_get_main_queue(), ^{ // Update some UI }); }]; NSLog(@"Device motion started"); } else { NSLog(@"Device motion unavailable"); } 

迅速

 // Ensure to keep a strong reference to the motion manager otherwise you won't get updates motionManager = CMMotionManager() if motionManager?.deviceMotionAvailable == true { motionManager?.deviceMotionUpdateInterval = 0.1; let queue = NSOperationQueue() motionManager?.startDeviceMotionUpdatesToQueue(queue, withHandler: { [weak self] (motion, error) -> Void in // Get the attitude of the device if let attitude = motion?.attitude { // Get the pitch (in radians) and convert to degrees. // Import Darwin to get M_PI in Swift print(attitude.pitch * 180.0/M_PI) dispatch_async(dispatch_get_main_queue()) { // Update some UI } } }) print("Device motion started") } else { print("Device motion unavailable"); } 

NSHipster (一如既往)是一个很好的信息来源,关于CMDeviceMotion的文章也不例外。