Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting accelerometer data in background using CoreMotion

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...

like image 486
Apollo Avatar asked Feb 22 '14 00:02

Apollo


People also ask

How do you get the accelerometer data on Apple Watch?

Direct access to the Apple Watch sensors (which include the accelerometer) is not possible. As always, if this is something you'd like, please file a request for it at https://bugreport.apple.com. Save this answer. Show activity on this post.

How accurate is iPhone accelerometer?

The coefficient of variation was less than 3% at velocities from 30°/s to 120°/s and less than 7% at 150°/s. Conclusions: The app was highly accurate and precise.

How does Apple Watch accelerometer work?

Apple claims the accelerometer is capable of measuring up to 256 Gs, allowing the device to detect the extreme impacts of a crash. It samples motion four times faster at over 3,000 times a second, so it can sense the precise moment of impact.


1 Answers

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;
            }
        }];
like image 85
fjlksahfob Avatar answered Sep 23 '22 11:09

fjlksahfob