2015-03-31 77 views
0

我正在編寫一個iOS應用程序,用於統計用戶在使用按鈕激活時所採取的步驟。我現在能夠計算這些步驟,但我希望能夠通過用戶請求暫停和重置步驟計數器。我對XCode並不是很有經驗,所以可能有一種簡單的方法來做到這一點。我用#2類似於一個代碼可供選擇:在iOS Core Motion中暫停,恢復和重置步驟計數

#import "ViewController.h" 
 
#import "DTStepModelController.h" 
 
#import <CoreMotion/CoreMotion.h> 
 

 
@interface ViewController() 
 

 
@property (weak, nonatomic) IBOutlet UILabel *stepsCountingLabel; @property (nonatomic, strong) CMStepCounter *cmStepCounter; 
 
@property (nonatomic, strong) NSOperationQueue *operationQueue; 
 

 

 
@end 
 

 
@implementation ViewController 
 
{ 
 
    DTStepModelController *_stepModel; 
 
} 
 

 

 
- (NSOperationQueue *)operationQueue 
 
{ 
 
    if (_operationQueue == nil) 
 
    { 
 
     _operationQueue = [NSOperationQueue new]; 
 
    } 
 
    return _operationQueue; 
 
} 
 

 
- (void)updateStepCounterLabelWithStepCounter:(NSInteger)countedSteps 
 
{ 
 
    self.stepsCountingLabel.text = [NSString stringWithFormat:@"%ld", (long)countedSteps]; 
 
} 
 

 
- (IBAction)StartCountingSteps:(id)sender { 
 
    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]; 
 
      }]; 
 
     }]; 
 
    } 
 

 
}

任何瞭解,或suggessions?

回答

0

我能找到我的問題的答案。請注意,如果您使用的是iOS 8.2或更高版本,Apple的問題將停止支持,並且問題中的以前的代碼將無法使用。在新的iOS版本中,您可以查詢M7計數器並保存該值,存儲該值,然後從舊的值中減去新的值。

無論如何,對於上面的代碼,您可以停止計數器(PauseCounter方法),但它會將計數器重置爲零。

-(IBAction) PauseCounting: (id) sender { 
 
    [self.cmStepCounter stopStepCountingUpdates]; 
 
} - (IBAction) ResumeCounting: (id) sender { 
 
    [self.cmStepCounter startStepCountingUpdatesToQueue: self.operationQueue updateOn: 1 withHandler:^(NSInteger numberOfSteps, NSDate * timestamp, NSError * error) { 
 
    [ 
 
     [NSOperationQueue mainQueue] addOperationWithBlock:^{ 
 
     [self updateStepCounterLabelWithStepCounter: numberOfSteps]; 
 
     } 
 
    ]; 
 
    }]; 
 

 
}