I want to get an array of nearby locations using mapkit framework. So when the user types in a textfield I call the following function.
- (void)searchForLocations:(NSString *)string
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(search:) object:nil];
[self performSelectorInBackground:@selector(search:) withObject:string];
}
- (void)search :(NSString *)string
{
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = string;
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.05;
span.longitudeDelta = 0.05;
region.span = span;
region.center = newLocation.coordinate;
request.region = region;
MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
if (response.mapItems.count == 0)
{
NSLog(@"No Matches");
}
else
{
NSLog(@"name = %@", item.name);
NSLog(@"Phone = %@", item.phoneNumber);
}
}];
}
As you can see I want to cancel the previous search if a new input text is coming. But the previous search is not cancelled. How can i cancel the previous search?
Thanks in advance.
There is a cancel method on MKLocalSearch. Have you tried that one?
Edit: Ah, sorry, I was being stupid. You need to keep a reference to your old search in some way in order to cancel it. Put it in a property which you can clear (i.e. set to nil) when the search is finished. Whenever you call the search function, cancel the previous search function (no "if" needed, nil swallows all), then create a new one
@property (nonatiomic, strong) MKLocalSearch *previousSearch;
- (void)search :(NSString *)string
{
[self.previousSearch cancel];
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = string;
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.05;
span.longitudeDelta = 0.05;
region.span = span;
region.center = newLocation.coordinate;
request.region = region;
MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
self.previousSearch = nil;
if (response.mapItems.count == 0)
{
NSLog(@"No Matches");
}
else
{
NSLog(@"name = %@", item.name);
NSLog(@"Phone = %@", item.phoneNumber);
}
}];
self.previousSearch = search;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments