我想知道是否有人可以向我展示如何实现 CMStepCounter 的示例。(我已经查看了文档,但对于如何实现仍然有些困惑)。
每次采取步骤时,我都希望在我的视图上更新 UILabel。我还希望让应用程序在关闭时继续计算步数。
我对 iOS 比较陌生,任何帮助将不胜感激 :) !
谢谢,瑞安
我想知道是否有人可以向我展示如何实现 CMStepCounter 的示例。(我已经查看了文档,但对于如何实现仍然有些困惑)。
每次采取步骤时,我都希望在我的视图上更新 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 的块会延迟更新 numberOfSteps。