我试图在我的应用程序中执行一个方法,但只有在手机在给定的时间间隔内处于正确的加速度计方向之后。我遇到的问题是每次更新加速度计时,计时器都会重置。我无法弄清楚如何触发仅启动一次的时间,而不是每次更新加速度计时。
// 在 ViewController.h 中
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>
@interface ViewController : UIViewController
{
float timeTest;
}
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) NSTimer *timerObject;
- (void) testMethod;
- (void) addTime;
- (void) startTimer;
@end
// 在 ViewController.m 中
#import "ViewController.h"
@implementation ViewController
@synthesize motionManager;
@synthesize timerObject;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.motionManager = [[CMMotionManager alloc]init];
[self testMethod];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) testMethod
{
if ([self.motionManager isAccelerometerAvailable])
{
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData,NSError *error)
{
if (ABS(accelerometerData.acceleration.x) < 0.30 && ABS(accelerometerData.acceleration.y) < 0.30 && ABS(accelerometerData.acceleration.z) > 0.70) // Phone is flat and screen faces up
{
NSLog(@"Correct position.");
[self startTimer]; // Problem here. This just continually resets the timer for each accelerometer update.
}
else
{
NSLog(@"Incorrect position.");
[timerObject invalidate];
timeTest = 0.0;
}
}];
}
else
{
NSLog(@"Accelerometer is not available.");
}
}
- (void) addTime
{
timeTest = timeTest + 0.1;
if (timeTest == 3.0)
{
[timerObject invalidate];
// Where code for next action would go. For feedback, just simply set the screen to green.
self.view.backgroundColor = [UIColor greenColor];
}
}
- (void) startTimer
{
timeTest = 0.0;
timerObject = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(addTime) userInfo:nil repeats:YES];
}
@end
任何帮助都会很棒!