5

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

1 Answer 1

9

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.

5
  • Thanks, I have noticed however that the app doesn't seem to update the amount of steps that have been taken when the app is closed/phone is locked. Is there a way to do this ? Thanks again.
    – Ryan
    Jan 6, 2014 at 15:48
  • 1
    Did you specify, Required background modes in your app's plist file?
    – ldindu
    Jan 6, 2014 at 16:48
  • No, I've found a list but am unsure which one to select :) Thanks,
    – Ryan
    Jan 6, 2014 at 17:05
  • Based on the Apple documentation that I have read about CMStepCounter, it hasn't mentioned anything about you can use CMStepCounter on background mode.
    – ldindu
    Jan 7, 2014 at 8:59
  • Fair enough, I wonder how other apps do it like Pedometer++. I wonder if they query to see if there are any updates when the app re-opens. (– queryStepCountStartingFrom:to:toQueue:withHandler:). Do you know how this works? Thanks for all your help to far :)
    – Ryan
    Jan 7, 2014 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.