我有以下代码跟踪用户的位置,并检测用户是否在JSON文件中的指定事件之一,通过匹配当前用户位置的长和拉与长当事件开始时间与当前iPhone时间相等时,然后执行以下指令,触发NSTimer持续5分钟,5分钟后调用此方法onTick(),计算开始时间并且当前时间超过5分钟,如果超过5分钟,则将该事件设置为参加。问题是,当我在iPhone上测试它时,它确实有效,但对于时间间隔超过5分钟的所有事件,即使我只想为当前用户在当时的事件工作!任何人都可以plzzz对我解释这是为什么发生,什么可能是解决..我真的糊涂..测试与位置跟踪NSTimer
这里是我的代码:
.h file
@property (nonatomic, strong) Event *currentEvent;
@property (nonatomic, strong) CLLocation *currentEventLocation;
@property (nonatomic, strong) NSDate *arrivalDate;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) CLLocation *theNewLocation;
.m file
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
self.currentLocation = [locations lastObject];
if (self.currentEvent) {
if ([self.arrivalDate timeIntervalSinceNow]<60*3) {
if ([self.currentEventLocation distanceFromLocation:self.theNewLocation]<100) {
[self.currentEvent setHasATTENDED:[NSNumber numberWithBool:TRUE]];
}
}
}
self.currentLocation = self.theNewLocation;
for (Event *event in [self loadTodaysEvents]) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
NSDate *currentTime = [NSDate date];
[dateFormatter setDateFormat:@"HH:mm"];
NSString *resultString = [dateFormatter stringFromDate:currentTime];
NSString *eventStartTime = event.startingTime;
// distance
CLLocationDegrees lat = [event.lat doubleValue];
CLLocationDegrees lon = [event.longi doubleValue];
CLLocation *evLocation = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
double distance = [evLocation distanceFromLocation:self.theNewLocation];
// CLOSE !
if (distance <= 100 && [resultString isEqualToString:eventStartTime]) {
self.arrivalDate = currentTime;
self.currentEvent = event;
self.currentEventLocation = evLocation;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 180.0
target: self
selector: @selector(onTick:)
userInfo: nil
repeats: NO];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:timer forMode: NSDefaultRunLoopMode];
}
}
}
- (void)onTick:(NSTimer *)timer
{
[self locationManager:nil didUpdateLocations:@[self.currentLocation]];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
由于计时器已经安排,你不需要它的广告向runloop! –
你为什么要将[NSDate日期]翻译成NSString并回到NSDate? –
我不认为这条线是有道理的!请确保您确实要检查此事件的开始时间是否与当前时间相同! [resultString isEqualToString:eventStartTime] –