8

我在应用程序中的要求是我必须检测从应用程序计数的步骤,即使应用程序在后台运行,这也应该继续。我研究过这个;通常苹果不允许在后台使用加速度计数据,但我想使用 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 项选择应用程序注册以进行位置更新”。

4

0 回答 0