iOS 10 下在后台更新位置和加速度计

Location and accelerometer updates in the background under iOS 10

我的应用程序收集位置和加速度计信息,并在用户请求时在后台继续这样做。加速度计信息以大约 100 Hz 的频率收集,以高速率收集是至关重要的。该应用程序在 iOS 的旧版本下运行良好,但在 iOS 10 下失败。我正在寻找一种在后台继续收集加速度计信息的方法。

使用的方法与Receive accelerometer updates in background using CoreMotion framework类似。我启动位置管理器:

latitude = 0.0;
longitude = 0.0;
altitude = 0.0;
horizontalAccuracy = -1.0;
verticalAccuracy = -1.0;
if (locationManager == nil && [CLLocationManager locationServicesEnabled]) {
    self.locationManager = [[CLLocationManager alloc] init];

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [locationManager requestWhenInUseAuthorization];
    }

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.pausesLocationUpdatesAutomatically = NO;
    [locationManager startUpdatingLocation];
}

我执行locationManager:didUpdateLocations:

- (void) locationManager: (CLLocationManager *) manager didUpdateLocations: (NSArray *) locations {
    printf("locationManager:didUpdateLocations:\n");
    CLLocation *location = locations.lastObject;
    latitude = location.coordinate.latitude;
    longitude = location.coordinate.longitude;
    altitude = location.altitude;
    horizontalAccuracy = location.horizontalAccuracy;
    verticalAccuracy = location.verticalAccuracy;
}

我启动运动管理器:

motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = 1.f/trialFrequency;
[[NSOperationQueue mainQueue] setMaxConcurrentOperationCount: 10];
[motionManager startAccelerometerUpdatesToQueue: [NSOperationQueue mainQueue]
                                    withHandler: ^(CMAccelerometerData *accelerometerData, NSError *error) {
                                        // Flag any error.
                                        if (error) {
                                            NSLog(@"error getting accelerometer update: %@", error);
                                        }
                                        <<<process data>>>
                                    }
 ];

已检查目标、功能、背景模式、位置更新。

在iOS9及之前,运动信息以100Hz左右的速率记录没有问题,但在iOS10下,运动信息一进入应用程序就停止背景。

有什么办法可以让iOS10下后台继续的运动信息?

从 iOS9 开始,需要一个新的调用来启用位置事件的后台处理。它可用于打开和关闭后台处理,但默认为关闭,因此必须手动设置才能恢复 iOS 8 和之前代码中的后台处理。

在设置位置管理器时添加此行以允许后台处理:

    locationManager.allowsBackgroundLocationUpdates = YES;