Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement CMStepCounter CoreMotion - M7 Chip

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

like image 821
Ryan Avatar asked Jan 05 '14 16:01

Ryan


1 Answers

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.

like image 58
ldindu Avatar answered Nov 13 '22 06:11

ldindu