使用CMPedometer进行实时更新(CoreMotion) [英] Live Updates with CMPedometer (CoreMotion)

查看:198
本文介绍了使用CMPedometer进行实时更新(CoreMotion)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个主题资源非常有限(CMPedometer)。我想知道这里是否有人设法让这个正常工作。我的代码相当简单,并且比我正在尝试的更多。基本上,步数计数器不会增加用户采取的每一步。

I've found very limited resources on this topic (CMPedometer). I was wondering if anyone here has managed to get this to work properly. My code is fairly simple, and has more than what I'm trying to do. Basically, the step counter does not increment EVERY step a user takes.

它实际上是跟踪用户采取的每一步,但它更新得太慢,我无法弄清楚原因。我甚至尝试使用NSTimer来请求每半秒更新一次标签。我想尝试让步骤计数器在用户采取步骤时进行更新。这是我的代码......

It actually is tracking every step the user takes but it updates so slowly and I can't figure out why. I even tried using NSTimer to make a request to update the labels every half a second. I want to try to get the step counter to update as a user takes a step. Here is my code...

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (nonatomic, strong) CMPedometer    *pedometer;
@property (nonatomic, weak) IBOutlet UILabel *startDateLabel;
@property (nonatomic, weak) IBOutlet UILabel *endDateLabel;
@property (nonatomic, weak) IBOutlet UILabel *stepsLabel;
@property (nonatomic, weak) IBOutlet UILabel *distanceLabel;
@property (nonatomic, weak) IBOutlet UILabel *ascendedLabel;
@property (nonatomic, weak) IBOutlet UILabel *descendedLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([CMPedometer isStepCountingAvailable]) {
        self.pedometer = [[CMPedometer alloc] init];
        [NSTimer scheduledTimerWithTimeInterval:0.5f
                                         target:self
                                       selector:@selector(recursiveQuery)
                                       userInfo:nil
                                        repeats:YES];
    } else {
        NSLog(@"Nothing available");
        self.startDateLabel.text = @"";
        self.endDateLabel.text   = @"";
        self.stepsLabel.text     = @"";
        self.distanceLabel.text  = @"";
        self.ascendedLabel.text  = @"";
        self.descendedLabel.text = @"";
    }

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.pedometer startPedometerUpdatesFromDate:[NSDate date]
                                      withHandler:^(CMPedometerData *pedometerData, NSError *error) {
                                          dispatch_async(dispatch_get_main_queue(), ^{
                                              NSLog(@"data:%@, error:%@", pedometerData, error);
                                          });
                                      }];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.pedometer stopPedometerUpdates];
}

- (NSString *)stringWithObject:(id)obj {
    return [NSString stringWithFormat:@"%@", obj];
}

- (NSString *)stringForDate:(NSDate *)date {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateStyle = NSDateFormatterShortStyle;
    formatter.timeStyle = NSDateFormatterShortStyle;

    return [formatter stringFromDate:date];
}

- (void)queryDataFrom:(NSDate *)startDate toDate:(NSDate *)endDate {
    [self.pedometer queryPedometerDataFromDate:startDate
                                        toDate:endDate
                                   withHandler:
     ^(CMPedometerData *pedometerData, NSError *error) {

         NSLog(@"data:%@, error:%@", pedometerData, error);

         dispatch_async(dispatch_get_main_queue(), ^{
             if (error) {
                 NSLog(@"Error = %@",error.userInfo);
                 self.startDateLabel.text = @"";
                 self.endDateLabel.text   = @"";
                 self.stepsLabel.text     = @"";
                 self.distanceLabel.text  = @"";
                 self.ascendedLabel.text  = @"";
                 self.descendedLabel.text = @"";
             } else {
                 self.startDateLabel.text = [self stringForDate:pedometerData.startDate];
                 self.endDateLabel.text   = [self stringForDate:pedometerData.endDate];
                 self.stepsLabel.text     = [self stringWithObject:pedometerData.numberOfSteps];
                 self.distanceLabel.text  = [NSString stringWithFormat:@"%.1f[m]", [pedometerData.distance floatValue]];
                 self.ascendedLabel.text  = [self stringWithObject:pedometerData.floorsAscended];
                 self.descendedLabel.text = [self stringWithObject:pedometerData.floorsDescended];
             }
         });
     }];
}

- (void)recursiveQuery {
    NSDate *to   = [NSDate date];
    NSDate *from = [to dateByAddingTimeInterval:-(24. * 3600.)];
    [self queryDataFrom:from toDate:to];
}

提前感谢您的任何反馈!

Thanks in advance for any feedback!

编辑

似乎适用于实时更新的方法如下..

It seems the appropriate method to use for live updates is the following..

- (void)liveSteps {
    [self.pedometer startPedometerUpdatesFromDate:[NSDate date]
                                      withHandler:^(CMPedometerData *pedometerData, NSError *error) {
                                          dispatch_async(dispatch_get_main_queue(), ^{
                                              NSLog(@"Steps %@",pedometerData.numberOfSteps);
                                          });
                                      }];
}

然而,即使这种情况严重延迟。当用户采取措施时,有没有人知道如何正确使用它来实质更新?

However, even this is severely delayed. Does anyone have any idea how to use this properly to essentially update as the user takes a step?

推荐答案

我只能确认你的发现。我也希望获得真实的实时信息。就像在这一点上看来,API无法做到这一点;甚至通过强制更新到队列,同步,异步等。

I can only confirm your findings. I also wanted to get "true" realtime information. As it seems at this point, the API is not capable of this; even by forcing the updates into a queue, sync, async, etc.

对于参考和其他有这个问题的人,这里是我使用的基于Swift 3和Xcode的代码8.2。在检查了CMPedometer.isStepCountingAvailable()之后,我只是在相关的viewcontroller中应用了这部分代码。

For references and others with this question, here is the code I use based on Swift 3 and Xcode 8.2. I simply apply this portion of code in the concerned viewcontroller, after checking the CMPedometer.isStepCountingAvailable().

正如你所看到的,我已经包含了一个小动画来更新UILabel更流畅。

As you can see, I've included a small animation to update the UILabel in a more fluid manner.

    // Steps update in near realtime - UILabel
    self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in

        DispatchQueue.main.async(execute: { () -> Void in
            if(error == nil){
                self.todaySteps.text = "\(data!.numberOfSteps)"
                // Animate the changes of numbers in the UILabel
                UILabel.transition(with: self.todaySteps,
                                   duration: 0.50,
                                   options: .transitionCrossDissolve,
                                   animations: nil,
                                   completion: nil)
            }
        })
    }

这篇关于使用CMPedometer进行实时更新(CoreMotion)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆