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

Mobiletainment
  • 22,201
  • 9
  • 82
  • 98
Fudgey
  • 3,793
  • 7
  • 32
  • 53

1 Answers1

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.

ldindu
  • 4,270
  • 2
  • 20
  • 24
  • 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. – Fudgey Jan 06 '14 at 15:48
  • 1
    Did you specify, Required background modes in your app's plist file? – ldindu Jan 06 '14 at 16:48
  • No, I've found a list but am unsure which one to select :) Thanks, – Fudgey Jan 06 '14 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 07 '14 at 08: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 :) – Fudgey Jan 07 '14 at 10:27