Как получить данные акселерометра в фоновом режиме, используя движение ядра?

Мое требование к приложению состоит в том, что я должен обнаруживать подсчет шагов из приложения, и это должно продолжаться, даже если приложение работает в фоновом режиме. Я изучал это; обычно Apple не позволяет использовать данные акселерометра в фоновом режиме, но я думаю, что с помощью Core Motion мы можем добиться этого.

Вот мой код:

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.*/



    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4

        if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking

            backgroundSupported = [UIDevice currentDevice].multitaskingSupported;

            UIApplication *application = [UIApplication sharedApplication];//Get the shared application instance

            __block UIBackgroundTaskIdentifier background_task; //Create a task object
            background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {


                NSAssert(background_task == UIBackgroundTaskInvalid, nil);

                [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                //System will be shutting down the app at any point in time now

            }];


            //Background tasks require you to use asyncrous tasks
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                //Perform your tasks that your application requires


                dispatch_async(dispatch_get_main_queue(), ^{
                    if (background_task != UIBackgroundTaskInvalid)
                    {
                        [application endBackgroundTask:background_task];
                        background_task = UIBackgroundTaskInvalid;
                    }
                });
                locationManager.delegate = self;//or whatever class you have for managing location
                [locationManager startMonitoringSignificantLocationChanges];
                [locationManager startUpdatingLocation];
                NSLog(@"\n\nRunning in the background!\n\n");
               // [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
               // background_task = UIBackgroundTaskInvalid; //Invalidate the background_task

            });
        }
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{

         CLLocation *loc = [locations lastObject];
         float latitudeMe = loc.coordinate.latitude;
         float longitudeMe = loc.coordinate.longitude;

         NSOperationQueue *theQueue = [[NSOperationQueue alloc] init];

         CMAccelerometerData *_returnedData = [[CMAccelerometerData alloc] init];
         CMMotionManager  *_motionManager = [[CMMotionManager alloc] init];

        [_motionManager startAccelerometerUpdatesToQueue:theQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {


            int x = _motionManager.accelerometerData.acceleration.x;
            int y = _motionManager.accelerometerData.acceleration.y;
            int z = _motionManager.accelerometerData.acceleration.z;

            NSLog(@"X: %i, Y: %i, z: %i", x, y,z);


            //[self changeFilter:[HighpassFilter class]];
            //[filter addAcceleration:acceleration];
            const float violence = 1.70;
            float magnitudeOfAcceleration = sqrt (x*x + y*y + z*z);

            //float magnitudeOfAcceleration = sqrt (filter.x*filter.x + filter.y * filter.y + filter.z * filter.z);
            BOOL shake = magnitudeOfAcceleration > violence;
            if (shake)
            {
                step++;
            }
             NSUserDefaults *defalut = [NSUserDefaults standardUserDefaults];
            [defalut setObject:[NSString stringWithFormat:@"%i",step] forKey:@"Stepscounting"];

        }];

}

Может ли кто-нибудь помочь мне, где я ошибаюсь?

Я уже добавил в plist-файл "Необходимые фоновые режимы-> и в пункте 0 выберите Регистрация приложения для обновления местоположения".


person i_Intiution    schedule 04.11.2012    source источник
comment
Вызывается ли didUpdateLocations вообще? Вы просите о значительных изменениях, поэтому вам придется пройти пару кварталов, прежде чем получить обратный вызов, я думаю.   -  person Dabrut    schedule 29.05.2013
comment
@ Дэйв, да, я получаю координаты местоположения при обновлении местоположения. didUpdateLocations вызывается, когда мы идем. Проблема в том, что я не правильно подсчитываю шаги.   -  person i_Intiution    schedule 29.05.2013