我正在尝试探索CoreMotion
,并且正在尝试使用CMStepCounter
类来获取“步数”。这是我实现view controller
以获得stepCounts
的方式
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *stepsCountingLabel;
@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];
}];
}];
}
else
{
self.stepsCountingLabel.text = @"NO STEP COUNTING AVAILABLE";
}
}
- (void)updateStepCounterLabelWithStepCounter:(NSInteger)countedSteps
{
self.stepsCountingLabel.text = [NSString stringWithFormat:@"%ld", (long)countedSteps];
}
但是,当我走路携带设备时,我没有任何更新,但是当我晃动设备时,它给了我一些随机的
numberOfSteps
计数。如果我错过了一些东西,请告诉我。 最佳答案
请尝试以下方法。我认为它将起作用。从viewdidload调用startStepCalculations
方法。我正在计算1天的步骤。
- (void)startStepCalculations {
if (!self.stepCounter) {
self.stepCounter = [[CMStepCounter alloc] init];
}
if (![CMStepCounter isStepCountingAvailable]) {
return;
}
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit)
fromDate:[[NSDate alloc] init]];
[components setHour:-[components hour]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
NSDate *start = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0];
[components setHour:+24];
[components setMinute:0];
[components setSecond:0];
NSDate *end = [cal dateByAddingComponents:components toDate:start options:0];
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[self.stepCounter queryStepCountStartingFrom:start
to:end
toQueue:queue
withHandler:^(NSInteger numberOfSteps, NSError *error) {
if (error) {
NSLog(@"ERROR : %@",error.localizedDescription);
return;
}
self.steps = numberOfSteps;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:self.steps];
[self beginMonitoringForNewSteps];
}];
}
- (void)beginMonitoringForNewSteps {
if (!self.stepCounter) {
self.stepCounter = [[CMStepCounter alloc] init];
}
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[self.stepCounter startStepCountingUpdatesToQueue:queue
updateOn:1
withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
// calculate the total steps (today + new)
self.steps += (int)numberOfSteps;
//TODO badge number should be 1000 max
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:self.steps];
}];
}
让我知道它是否有效。
快乐编码!