Show an UIAlert when delegate in LocationManager takes too long
I'm trying to create an alert when my LocationManager takes too long. In its delegate method, I check the newLocation's timestamp to make sure it's something recent:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 1.0) { // process time if time is less than 1.0 seconds old.
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCount:) userInfo:nil repeats:YES];
return;
}
After some debugging, I realize that putting timer in that if block isn't right. What ends up happening is, the timer never invalidates, or rather my updateCount: method keeps running. I think what's happening is the delegate keeps getting called back with a bad time, then it keeps running more timers, so I get UIAlert after UIAlert.
I've used the same updateCount: method in a test project to create a 30 second timer and invalidate it and it works fine. Now however, I am stuck since I basically want to find the person's location, but if it takes too long (> 30 seconds), t开发者_开发百科hrow an alert. I'm not really sure where I should put this kind of code. It seemed to me to put it in the delegate where I'm making the check of the timestamp since that's the error condition I'm looking to keep track of. But that doesn't seem to be working well for me.
Is there a better place to put this kind of check? Or is there a better way to do this kind of task altogether? I'm pretty new to programming, so my knowledge is limited. TIA.
I think what you should be doing is- set the 30 second timer when you call [locationManager startUpdatingLocation];
Now, you can update your method to look something like-
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 1.0) { //good time found
//use this location
//either remove the 30 second timer or set a boolean
self.goodLocationFound = YES;
[locationManager stopUpdatingLocation];
}
In your timer method, you could do-
{
[locationManager stopUpdatingLocation];
if(self.goodLocationFound == NO)
{
//display alert
}
}
精彩评论