iOS Coremotion加速器在后台/睡眠模式下更新

iOS Coremotion加速器在后台/睡眠模式下更新,ios,objective-c,accelerometer,core-motion,Ios,Objective C,Accelerometer,Core Motion,当应用程序在后台运行/设备处于睡眠模式时,我需要加速器更新。有些应用程序会这样做,但我无法让它工作。 为此,我在appdelegate和ApplicationIdentinterBackground中调用了CoreMotion属性 -(void) startAccelerationUpdates { self.motionManager.deviceMotionUpdateInterval = 0.01; [self.motionManager startDeviceMotio

当应用程序在后台运行/设备处于睡眠模式时,我需要加速器更新。有些应用程序会这样做,但我无法让它工作。 为此,我在appdelegate和ApplicationIdentinterBackground中调用了CoreMotion属性

-(void) startAccelerationUpdates
{

    self.motionManager.deviceMotionUpdateInterval = 0.01;
    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                                       withHandler:^(CMDeviceMotion *motion, NSError *error){
         dispatch_async(dispatch_get_main_queue(), ^{
         NSLog(@"acceleration x %f", motion.userAcceleration.x);
         NSLog(@"acceleration y %f", motion.userAcceleration.y);
         NSLog(@"acceleration z %f", motion.userAcceleration.z);
         }
         );
         }
    ];
}

在app plist中,我将所需的后台模式放入app寄存器,以进行位置更新。当我将设备置于睡眠模式或后台时,日志中不会出现更新。当应用程序激活时,coremotion将开始登录。有人给我一个提示吗?谢谢。

这是因为您将其分派到主队列。要启用后台活动,应将其分派到全局队列:

dispatch_queue_t lowQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(lowQueue, ^{ ...

更新添加Swift版本:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
    // do some task
}

参考资料:

谢谢,但“分派到全局队列”也不起作用。此外,在应用程序的plist中,您是否使用了
所需的后台模式
->并在
项目0
中选择
应用程序注册位置更新
?是的。位置更新在后台/睡眠模式下工作。@simon您如何确定样本未被记录?在这种情况下,不要信任NSLog或任何类似的东西-尝试记录每个样本的时间戳,您会看到它是连续的。您的解决方案是否也可以在后台检测用户是否处于自动/跑步/步行状态?