How to use CMStepCounter
CMStepCounter
CMStepCounterクラスは歩数へのアクセスを提供する
歩数の計測を開始する
- (void)startStepCountingUpdatesToQueue:(NSOperationQueue *)queue updateOn:(NSInteger)stepCounts withHandler:(CMStepUpdateHandler)handler
Code example
// Check step counting available
if ([CMStepCounter isStepCountingAvailable]) {
__weak typeof(self) weakSelf = self;
// Create step counter
self.stepCounter = [[CMStepCounter alloc] init];
// Start step counting
[self.stepCounter startStepCountingUpdatesToQueue:[NSOperationQueue mainQueue]
updateOn:1
withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
weakSelf.stepCountLabel.text = [@(numberOfSteps) stringValue];
}];
}
歩数の計測を停止する
- (void)stopStepCountingUpdates
期間を指定して歩数を取得する(過去7日間まで取得可能)
- (void)queryStepCountStartingFrom:(NSDate )start to:(NSDate )end toQueue:(NSOperationQueue *)queue withHandler:(CMStepQueryHandler)handler
Code Example
// Check step counting available
if ([CMStepCounter isStepCountingAvailable]) {
__weak typeof(self) weakSelf = self;
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour fromDate:now];
[comps setHour:0];
NSDate *today = [gregorian dateFromComponents:comps];
[self.stepCounter queryStepCountStartingFrom:today
to:now
toQueue:[NSOperationQueue mainQueue]
withHandler:^(NSInteger numberOfSteps, NSError *error) {
NSLog(@"------------------------------------------");
NSLog(@"%s : %d", __PRETTY_FUNCTION__, __LINE__);
NSLog(@"numberOfSteps : %d", (int)numberOfSteps);
NSLog(@"error : %@", error);
weakSelf.totalStepsLabel.text = [@(numberOfSteps) stringValue];
}];
}