Question

I was wondering if anyone could show me an example of how to implement CMStepCounter. (I've looked at the documentation but am still left a little confused as to how to implemented).

I'm looking to update a UILabel on my View every time a step is taken. I am also looking to let the app continue counting steps when it is closed.

I'm relatively new to iOS to any help would be greatly appreciated :) !

Thanks, Ryan

Was it helpful?

Solution

You should implement it as follows

#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

However note that, sometimes startStepCountingUpdatesToQueue's block will delay updating numberOfSteps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top