ios - 如何实现 CMStepCounter CoreMotion - M7 芯片

标签 ios objective-c counter core-motion apple-m7

我想知道是否有人可以向我展示如何实现 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/

相关文章:

objective-c - 带音频的计时器精度

ios - SDL 在 iOS 上保存屏幕截图

ios - 如何从网络服务加载数组?

ios - 我可以查明单元格何时排队吗?

ios - 在 objective-c 中使用 NsTimer 实现计数器

ios - 如何在 Sprite Kit 中对 Sprite 进行部分动画?

objective-c - 多个 AVAudioRecorder 实例

c# - 即使在删除性能类别后,RawFraction 性能计数器仍保持其状态

c - 在数组中输入变量时实现计数器

ios - 获取特定类型的所有 CKRecords