我是 iOS 编程新手。我想编写一个应用程序,在后台运行时可以持续访问 iPhone 6 的加速度计和气压传感器。
在我的研究中,我发现人们已经使用位置更新后台模式完成了它,但这只在应用程序暂停之前工作了 10 分钟(在 iOS 6 中变成了 3 分钟?)。我还阅读了有关使用音频背景模式播放静音作为解决该时间限制的方法的信息。不过,这似乎是一个不合标准的解决方案。
我想知道一个类似 Sleep Cycle 的应用程序是怎么来的?这样做,因为它似乎必须能够持续访问加速度计。
最佳答案
可以使用CoreMotion框架来完成。
你必须导入CoreMotion框架,然后 #import <CoreMotion/CoreMotion.h>
在你的appdelegate
.
这里motionManager
是 CMMotionManager
的对象.
xData, yData, zData
是用于存储加速度计数据的 double 值。
if (motionManager ==nil) {
motionManager= [[CMMotionManager alloc]init];
}
[motionManager startAccelerometerUpdates];
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
xData = accelerometerData.acceleration.x;
yData = accelerometerData.acceleration.y;
zData = accelerometerData.acceleration.z;
}];
您必须在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
中执行此操作.
然后您可以使用 xData, yData, zData
的这些值随心所欲 appdelegate
对象,即使在背景中。
关于ios - 在后台运行时访问 iOS 中的加速度计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941981/