而不是像这样使用for 循环,理论上您可以使用每两秒触发一次的重复NSTimer,然后在15 次迭代后使用invalidate 计时器。
但我不建议这样做,而是转向事件驱动模型,等待致电您的didUpdateLocations。如果 didUpdateLocations 尚未更新,则在两秒钟内检查是没有意义的。同样,在 30 秒内重复检查 15 次也是没有意义的,例如,如果您在 5 秒后获得了非常准确的位置。
我建议开始监控该位置,在随后调用didUpdateLocations 时观察这些位置,并检查CLLocation 中的horizontalAccuracy(它告诉您该位置的准确程度)。一旦达到所需的horizontalAccuracy,您就可以宣布成功(例如停止监视位置或其他)。如果需要,您还可以建立一个NSTimer,在 30 秒后自动关闭位置监控。
例如:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%s", __PRETTY_FUNCTION__);
[self startStandardUpdates];
// after 30 seconds, if we haven't found a location, declare success with whatever we got (if anything)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopStandardUpdates]; // stop monitoring location if you want
if (!self.foundLocation) {
if (self.bestLocation) {
NSLog(@"Didn't find perfect location, but location has accuracy of %.1f meters", self.bestLocation.horizontalAccuracy);
} else {
NSLog(@"Even after 30 seconds, did not find any locations!");
}
}
});
}
#pragma mark - Location Services
- (void)startStandardUpdates
{
// Create the location manager if this object does not
// already have one.
if (nil == self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Set a movement threshold for new events.
self.locationManager.distanceFilter = 5;
[self.locationManager startUpdatingLocation];
}
- (void)stopStandardUpdates
{
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSLog(@"%s: horizontalAccuracy = %.1f", __FUNCTION__, location.horizontalAccuracy);
if (location.horizontalAccuracy < 0) // not a valid location
return;
// this checks to see if the location is more accurate than the last;
// or you might just want to eliminate this `if` clause, because if
// you get updated location, you can probably assume it's better than
// the last one (esp if the user might be moving)
if (!self.bestLocation || location.horizontalAccuracy <= self.bestLocation.horizontalAccuracy) {
self.bestLocation = location;
}
if (location.horizontalAccuracy <= 5) { // use whatever you want here
NSLog(@"Found location %@", location);
self.foundLocation = YES;
[self stopStandardUpdates]; // stop it if you want
}
}
这使用以下属性:
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *bestLocation;
@property (nonatomic) BOOL foundLocation;