Search code examples
iosswiftdevicebackground-processcore-motion

Device motion updates in background


I am trying to get device motion updates on an iPhone or iPad in the background using CMMotionManager. I have reviewed all previous posts on this topic and thought that I had code that would work. My app also uses background audio, and this works properly in the foreground and background. In Info.plist, I have background audio and background location updates enabled.

For testing purposes, I have declared "var motionManager = CMMotionManager()" in AppDelegate, and included the following code in didFinishLaunchingWithOptions:

    motionManager.deviceMotionUpdateInterval = 0.10
    let queue = NSOperationQueue()
    motionManager.startDeviceMotionUpdatesToQueue(queue, withHandler: {
        data, error in

        let accelerationVector = sqrt(pow(data!.userAcceleration.x, 2) + pow(data!.userAcceleration.y, 2) + pow(data!.userAcceleration.z, 2))
        print("\(accelerationVector)")
    })

When I run the app on my device, the code executes in the foreground as expected, but when I press the home button, I get about 10 more readings before it stops. When I tap on the app icon, the readings start again. I have also placed breakpoints on the code in the handler, and get similar results.

What am I missing?


Solution

  • After doing more research, I figured out the problem. I was using to play background audio. This will play the audio in the background, but this does not keep my app running in the background. When I switched to using to play audio, the app runs in the background including the device motion updates.