Ios 使用CoreMotion在后台获取加速度计数据

Ios 使用CoreMotion在后台获取加速度计数据,ios,objective-c,core-motion,Ios,Objective C,Core Motion,我无法在后台接收加速计数据,尽管这个问题的解决方案似乎是正确的 每当应用程序位于前台时,都会记录执行,但每当我退出后台时,它就会停止运行。有人知道为什么会这样吗?我已经在后台模式中选中了“位置更新”…将此代码放在该行的正前方(在创建一个名为bgTaskID的UIBackgroundTaskIdentifier类型的成员变量之后): 这可以通过使用CoreMotion框架来完成。您必须导入CoreMotion框架,然后在appdelegate中导入 这里motionManager是CMMotion

我无法在后台接收加速计数据,尽管这个问题的解决方案似乎是正确的


每当应用程序位于前台时,都会记录执行,但每当我退出后台时,它就会停止运行。有人知道为什么会这样吗?我已经在后台模式中选中了“位置更新”…

将此代码放在该行的正前方(在创建一个名为bgTaskID的UIBackgroundTaskIdentifier类型的成员变量之后):


这可以通过使用CoreMotion框架来完成。您必须导入CoreMotion框架,然后在
appdelegate
中导入

这里motionManager是
CMMotionManager
的对象

扩展数据、yData、zData是存储加速计数据的双值

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)应用程序中执行此操作:(UIApplication*)应用程序使用选项完成启动:(NSDictionary*)启动选项


然后,您可以通过
appdelegate
对象在任何需要的地方使用
xData、yData、zData的这些值,即使是在后台也可以。

对我来说适用于iOS 7。你是说iOS 8吗?不,我是说iOS 7。我需要coreMotion信息,此解决方案是否也适用于coreMotion处理器在后台的自动/运行/行走信息?是否也可以启动gps以根据该信息获取位置?它适用于核心运动。你也可以用它来获取GPS信息。你真是太棒了!在iOS 9.3中工作得很好。为meI解决了一个大问题。我注意到,如果使用[NSOperationQueue mainQueue]而不是创建新队列,它似乎在后台工作。
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;
            }
        }];
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;
}];