2014-01-05 2 views
5

Мне было интересно, может ли кто-нибудь показать мне пример того, как реализовать CMStepCounter. (Я просмотрел документацию, но я все еще немного смутился относительно того, как реализовать).Как реализовать CMStepCounter CoreMotion - M7 Chip

Я ищу обновить UILabel на моем представлении каждый раз, когда делается шаг. Я также хочу, чтобы приложение продолжало считать шаги, когда оно закрыто.

Я относительно новичок в iOS для любой помощи будет очень благодарен :)!

Спасибо, Райан

ответ

9

Вы должны реализовать следующим образом

#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 будет задерживать обновляя numberOfSteps.

+0

Спасибо, я заметил, однако, что приложение, похоже, не обновляет количество шагов, которые были предприняты, когда приложение закрыто/телефон заблокирован. Есть ли способ сделать это ? Еще раз спасибо. – Ryan

+1

Вы указали, требуемые фоновые режимы в файле plist вашего приложения? – ldindu

+0

Нет, я нашел список, но не знаю, какой из них выбрать :) Спасибо, – Ryan

Смежные вопросы