我想知道是否有人可以向我展示如何实现 CMStepCounter 的示例。 (我查看了文档,但对于如何实现仍然有些困惑)。
每次执行一个步骤时,我都希望在我的 View 上更新一个 UILabel。我还希望让应用程序在关闭时继续计算步数。
我是 iOS 的新手,如果有任何帮助我将不胜感激 :)!
谢谢, 瑞安
最佳答案
你应该按如下方式实现它
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *stepsCountingLabel; // Connect this outlet to your's label in xib file.
@property (nonatomic, strong) CMStepCounter *cmStepCounter;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@end
@implementation ViewController
- (NSOperationQueue *)operationQueue
{
if (_operationQueue == nil)
{
_operationQueue = [NSOperationQueue new];
}
return _operationQueue;
}
- (void)viewDidLoad
{
[super viewDidLoad];
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];
}];
}];
}
}
- (void)updateStepCounterLabelWithStepCounter:(NSInteger)countedSteps
{
self.stepsCountingLabel.text = [NSString stringWithFormat:@"%ld", (long)countedSteps];
}
@end
但是请注意,有时 startStepCountingUpdatesToQueue 的 block 会延迟更新 numberOfSteps。
关于ios - 如何实现 CMStepCounter CoreMotion - M7 芯片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20936207/