暂停,恢复和重置iOS Core Motion中的计数步骤

时间:2015-03-31 16:33:46

标签: ios xcode core-motion

我正在编写一个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];
             }];
         }];
    }

}
&#13;
&#13;
&#13;

任何见解或建议?

1 个答案:

答案 0 :(得分:0)

我能够找到问题的答案。请注意,如果您使用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];
      }
    ];
  }];

}