문제

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

올바른 솔루션이 없습니다

다른 팁

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;
            }
        }];

It can be done by using CoreMotion framework. You have to import CoreMotion framework, then #import <CoreMotion/CoreMotion.h> in your appdelegate.

Here motionManager is object of CMMotionManager.

xData, yData, zData are double values to store accelerometer data.

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;
}];

You have to do it in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions.

You can then use these value of xData, yData, zData where ever you want by appdelegate object, even in background.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top