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

Apo*_*llo 5 objective-c ios core-motion

我无法在后台接收加速计数据,尽管每个问题看似正确的解决方案iPhone上的Nike + GPS如何在后台接收加速度计更新?

[_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];
                                             });}];
Run Code Online (Sandbox Code Playgroud)

当应用程序在前台时,会记录执行,但每当我退出到后台时,它都会停止运行.有谁知道为什么会这样?我在后台模式中检查了"位置更新"...

fjl*_*fob 7

将此代码放在该行的前面(在创建名为bibTaskID的成员变量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;
            }
        }];
Run Code Online (Sandbox Code Playgroud)