2015-03-31 78 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]; 
 
     } 
 
    ]; 
 
    }]; 
 

 
}