I have an array of CLLocation objects I parsed from a file. I’d want to simulate that the user is moving along that route, and I have implemented this:
for (CLLocation *loc in simulatedLocs) {
[self moveUser:loc];
sleep(1);
}
This is the method called in the loop:
- (void)moveUser:(CLLocation*)newLoc
{
CLLocationCoordinate2D coords;
coords.latitude = newLoc.coordinate.latitude;
coords.longitude = newLoc.coordinate.longitude;
CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:coords];
annotation.title = @"User";
// To remove the previous location icon
NSArray *existingpoints = self.mapView.annotations;
if ([existingpoints count] > 0) {
for (CustomAnnotation *annotation in existingpoints) {
if ([annotation.title isEqualToString:@"User"]) {
[self.mapView removeAnnotation:annotation];
break;
}
}
}
MKCoordinateRegion region = { coords, {0.1, 0.1} };
[self.mapView setRegion:region animated:NO];
[self.mapView addAnnotation: annotation];
[self.mapView setCenterCoordinate:newLoc.coordinate animated:NO];
}
But only last location in the array and its region are displayed in the mapView when running the iPhone simulator. I’d like to simulate that user is “moving” each 1 sec, how could I do that?
Thanks!
Looping through all the locations all at once with a
sleepat each iteration won’t work because the UI will be blocked until the method the loop is in finishes.Instead, schedule the
moveUsermethod to be called individually for each location so that the UI is not blocked throughout the sequence. The scheduling can be done using anNSTimeror possibly something simpler and more flexible such as theperformSelector:withObject:afterDelay:method.Keep an index ivar to keep track of which location to move to each time
moveUseris called.For example:
The existing
moveUser:method does not have to be changed.Note that the user experience and code can be simplified if instead of removing and adding the annotation again every time, you add it once at the beginning and just change its
coordinateproperty at each “move”.