【问题标题】:Pausing, resuming and resetting steps counting in iOS Core Motion在 iOS Core Motion 中暂停、恢复和重置步数
【发布时间】:2015-03-31 16:33:45
【问题描述】:

我正在编写一个 iOS 应用程序,它计算用户在使用按钮激活时所采取的步骤。我现在可以计算步数,但我希望能够根据用户请求暂停和重置步数计数器。我对 XCode 没有那么丰富的经验,所以可能有一种简单的方法可以做到这一点。我使用了类似于 Stackoverflow 上的代码:

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

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *stepsCountingLabel;  @property (nonatomic, strong) CMStepCounter *cmStepCounter;
@property (nonatomic, strong) NSOperationQueue *operationQueue;


@end

@implementation ViewController
{
   DTStepModelController *_stepModel;
}


- (NSOperationQueue *)operationQueue
{
    if (_operationQueue == nil)
    {
        _operationQueue = [NSOperationQueue new];
    }
    return _operationQueue;
}

- (void)updateStepCounterLabelWithStepCounter:(NSInteger)countedSteps
{
    self.stepsCountingLabel.text = [NSString stringWithFormat:@"%ld", (long)countedSteps];
}

- (IBAction)StartCountingSteps:(id)sender {
    if ([CMStepCounter isStepCountingAvailable])
    {
        self.cmStepCounter = [[CMStepCounter alloc] init];
        [self.cmStepCounter startStepCountingUpdatesToQueue:self.operationQueue updateOn:1 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error)
         {
             [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                 [self updateStepCounterLabelWithStepCounter:numberOfSteps];
             }];
         }];
    }

}

有什么见解或建议吗?

【问题讨论】:

    标签: ios xcode core-motion


    【解决方案1】:

    我能够找到我的问题的答案。请注意,如果您使用的是 iOS 8.2 或更高版本,我的回答和问题中的先前代码将不起作用,因为 Apple 停止支持计步。在新的 iOS 版本中,您可以查询 M7 计数器并保存值,存储它,然后从旧值中减去新值。

    无论如何,对于上述代码,您可以停止计数器(PauseCounter 方法),但它会将计数器重置为零。

    -(IBAction) PauseCounting: (id) sender {
      [self.cmStepCounter stopStepCountingUpdates];
    } - (IBAction) ResumeCounting: (id) sender {
      [self.cmStepCounter startStepCountingUpdatesToQueue: self.operationQueue updateOn: 1 withHandler: ^ (NSInteger numberOfSteps, NSDate * timestamp, NSError * error) {
        [
          [NSOperationQueue mainQueue] addOperationWithBlock: ^ {
            [self updateStepCounterLabelWithStepCounter: numberOfSteps];
          }
        ];
      }];
    
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多