Getting accelerometer data in background using CoreMotion
core-motion, ios, objective-c
Solution
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;
}
}];
Problem
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...