Search code examples
iosobjective-caccelerometercore-motion

Receive accelerometer updates in background using CoreMotion framework


I'm using the following code to get accelerometer data (using CoreMotion framework):

CMMotionManager *motionManager = [[CMMotionManager alloc] init];    
motionManager.accelerometerUpdateInterval = 1.0 / 60.0;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
                                                 withHandler:^(CMAccelerometerData  *accelerometerData, NSError *error) {
                                                 NSLog(@"ACCELEROMETER DATA = %@",accelerometerData);
                                                 }];

When the app is in foreground mode, I'm receiving the log, but when it enters background, I receive the log only when the music in the app is playing. I've added the following to app info plist file:

- Required background modes
   - App registers for location updates
   - App plays audio or streams audio/video using AirPlay

The question is: how can I receive accelerometer updates in background, when the music is not playing?


Solution

  • You can not only use accelerometer for fetching data from background,

    And as you say your App registers for location updates , start location manager in the foreground.

    Implementing Long-Running Background Tasks

    For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

    1. Apps that play audible content to the user while in the background, such as a music player app
    2. Apps that record audio content while in the background.
    3. Apps that keep users informed of their location at all times, such as a navigation app
    4. Apps that support Voice over Internet Protocol (VoIP)
    5. Apps that need to download and process new content regularly
    6. Apps that receive regular updates from external accessories