【问题标题】:Getting accelerometer data in background using CoreMotion使用 CoreMotion 在后台获取加速度计数据
【发布时间】:2014-03-23 18:15:14
【问题描述】:

我无法在后台接收加速度计数据,尽管这个问题How Nike+ GPS on iPhone receives accelerometer updates in the background? 的解决方案看似正确

[_motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
                                         withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
                                             dispatch_async(dispatch_get_main_queue(), ^{
                                                 NSLog(@"perform");
                                                 [(id) self setAcceleration:accelerometerData.acceleration];
                                                 [self performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:NO];
                                             });}];

每当应用程序在前台时,都会记录执行,但每当我退出到后台时,它就会停止运行。有谁知道为什么会这样?我已经在后台模式中检查了“位置更新”...

【问题讨论】:

  • 我注意到如果您使用 [NSOperationQueue mainQueue] 而不是创建新队列,它似乎在后台工作。

标签: ios objective-c core-motion


【解决方案1】:

将此代码放在该行的前面(在创建一个名为 bgTaskID 的 UIBackgroundTaskIdentifier 类型的成员变量之后):

UIApplication *application = [UIApplication sharedApplication];
        __weak __typeof(&*self)weakSelf = self;
        self.bgTaskID = [application beginBackgroundTaskWithExpirationHandler:^{
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;

            NSLog(@"BG TASK EXPIRED!");

            if (strongSelf) {
                [application endBackgroundTask:strongSelf.bgTaskID];
                strongSelf.bgTaskID = UIBackgroundTaskInvalid;
            }
        }];

【讨论】:

  • 对我来说适用于 iOS 7。你是说 iOS 8 吗?
  • 不,我的意思是 IOS 7。我需要 coreMotion 信息,这个解决方案是否也适用于后台 CoreMotion 处理器的 Automotive/running/walking 信息?是否也可以启动例如gps 根据该信息获取位置?
  • 它适用于核心运动。您还可以使用它来获取 GPS 信息。
  • 你太棒了!在 iOS 9.3 中运行良好。为我解决了一个大问题
【解决方案2】:

可以使用 CoreMotion 框架来完成。您必须导入 CoreMotion 框架,然后在您的 appdelegate 中导入 #import <CoreMotion/CoreMotion.h>

这里的motionManager是CMMotionManager的对象。

xData, yData, zData 是存储加速度计数据的双精度值。

if (motionManager ==nil) {
    motionManager= [[CMMotionManager alloc]init];
}
[motionManager startAccelerometerUpdates];

[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
    xData = accelerometerData.acceleration.x;
    yData = accelerometerData.acceleration.y;
    zData = accelerometerData.acceleration.z;
}];

您必须在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 中进行操作。

然后,您可以通过appdelegate 对象在任何您想要的地方使用xData, yData, zData 的这些值,即使在后台也是如此。

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多