我正在使用 coremotion 在后台实现加速度计数据。我在后台获取数据,但 x、y、z 坐标的值不正确。这是我的代码。
- (void)applicationWillResignActive:(UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
if (isInBackground)
{
[self sendBackgroundLocationToServer:newLocation];
}
}
-(void) sendBackgroundLocationToServer:(CLLocation *)location
{
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
}];
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.20;
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++;
NSLog(@"---------------");
}
NSUserDefaults *defalut = [NSUserDefaults standardUserDefaults];
NSLog(@"steps in background: %i",step );
if([defalut objectForKey:@"Stepscounting"]){
int f = [[defalut objectForKey:@"Stepscounting"] intValue];
step+=f;
}
[defalut setObject:[NSString stringWithFormat:@"%i",step] forKey:@"Stepscounting"];
}];
// AFTER ALL THE UPDATES, close the task
if (background_task != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:background_task];
background_task = UIBackgroundTaskInvalid;
}
}
使用这个我得到坐标,但值不正确。谁能告诉我这背后的原因是什么。我不明白为什么会这样。提前致谢。