How Nike+ GPS on iPhone receives accelerometer updates in the background?

懵懂的女人 提交于 2019-12-27 16:44:42

问题


The new Nike+ GPS application for iOS 5 is able to process accelerometer events in the background (thus allowing for indoor treadmill tracking). How is this possible? When I put my application in background, it ceases receiving events. I use the standard UIAccelerometer API.


回答1:


For the sake of providing an answer to this question, even though it is already self answered...

"If you use the newer Core Motion API, you can receive updates in the background."

Here is an example:

- (void)startAccelerationCollection {
    [self.motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
                                             withHandler:^(CMAccelerometerData *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.accelerometerReadings addObject:data];
        });
    }];
}



回答2:


When the the block with update of pedometer, I call the method to turn Off and turn On the GPS. For me it fixed the problem when the user press home and stay for one hour listening music on spotify.

Don't forget to enable Project Settings -> Capabilities -> Background modes - > Location updates

    import CoreLocation
    import CoreMotion


    //turn Off and turn On GPS
    private func apelacaoRenovarGPSLigado() {

    LocationManager.sharedInstance.stopUpdatingLocation()
    let locationManager = LocationManager.sharedInstance
    locationManager.autoUpdate = true
    locationManager.startUpdatingLocationWithCompletionHandler { (location, status, verboseMessage, error) -> () in

    }
}

private func startPedometer()
{
    if CMPedometer.isDistanceAvailable()
    {
        if self.pedometer == nil
        {
            self.pedometer = CMPedometer()
        }

        self.pedometer!.startPedometerUpdatesFromDate(NSDate()) { (data, error) in

            dispatch_async(dispatch_get_main_queue(), {

                print("DISTANCIA PARCIAL \(data!.distance!)")

                print("DIFERENCA \(data!.distance!.doubleValue - (self.totalDistance + self.subtotalDistance))")
                self.delegate!.trackerDistanceDidChanged((data!.distance!.doubleValue - (self.totalDistance + self.subtotalDistance)) / 1000.0)
                self.subtotalDistance = data!.distance!.doubleValue

                self.apelacaoRenovarGPSLigado()

            })

        }
    }
    else
    {
        self.delegate!.trackerDeviceNotSupported()
    }
}


来源:https://stackoverflow.com/questions/8716466/how-nike-gps-on-iphone-receives-accelerometer-updates-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!