使用CoreMotion在后台获取加速度计数据 [英] Getting accelerometer data in background using CoreMotion
问题描述
我无法在后台接收加速计数据,尽管每个问题看似正确的解决方案 iPhone上的Nike + GPS如何在后台接收加速度计更新?
I'm unable to receive accelerometer data in the background, despite the seemingly correct solution per this question How Nike+ GPS on iPhone receives accelerometer updates in the background?
[_motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"perform");
[(id) self setAcceleration:accelerometerData.acceleration];
[self performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:NO];
});}];
每当应用程序在前台时都会记录执行,但每当我退出到后台时,它都会停止运行。有谁知道为什么会这样?我在背景模式中检查了位置更新...
perform is logged whenever the app is in the foreground, but whenever I exit out to background it stops running. Does anyone have any idea why this might be? I've checked "Location Updates" in Background Modes...
推荐答案
将此代码放在该行的前面(之后)制作一个名为bgTaskID的成员变量,类型为UIBackgroundTaskIdentifier):
Put this code right in front of that line (after making a member variable called bgTaskID of type UIBackgroundTaskIdentifier):
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(&*self)weakSelf = self;
self.bgTaskID = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
NSLog(@"BG TASK EXPIRED!");
if (strongSelf) {
[application endBackgroundTask:strongSelf.bgTaskID];
strongSelf.bgTaskID = UIBackgroundTaskInvalid;
}
}];
这篇关于使用CoreMotion在后台获取加速度计数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!