【发布时间】:2014-03-31 21:25:12
【问题描述】:
我有以下代码,它跟踪用户位置并通过将当前用户位置的经度和纬度与今天事件的经度和纬度相匹配来检测用户是否处于 JSON 文件中的指定事件之一 + when事件开始时间等于当前 iPhone 时间然后执行以下指令触发 NSTimer 5 分钟,5 分钟后调用此方法 onTick() 它将计算开始时间和当前时间之间的差异 5 分钟过去了,如果仍然超过 5 分钟,则将此事件设置为已参加。问题是当我在我的 iPhone 上测试它时它确实有效,但是对于时间间隔超过 5 分钟的所有事件,即使我只想为用户当时所在的当前事件工作!任何人都可以为我解释为什么会发生这种情况以及可能的解决方案..我真的很困惑..
这是我的代码:
.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 date] 转换为 NSString 并返回到 NSDate?
-
我认为这条线没有意义!请确保您确实要检查此事件的开始时间是否与当前时间相同! [resultString isEqualToString:eventStartTime]
-
@NilsZiehn 所以你说 runloop 是导致所有间隔超过 5 分钟的事件被参加的人?所以通过删除它,只有真正参加过的会被设置为参加过??我认为 onTick() 方法有问题!
-
@NilsZiehn NSDate 是我的错。我知道我不应该那样做;p
标签: ios iphone nstimer cllocationmanager