问题
I am developing an app in which user can search for a point of interests, pick a search result and then the MKMapView will be centered to the result coordinate.
My question is how to make autocompletion happen? I have did research on MKLocalSearch
and MKLocalSearchRequest
, and it seems that is Apple suggested API for location search on iOS6.1+. However I cannot find any examples with autocompletion or suggestions with MKLocalSearch
and MKLocalSearchRequest
. Is it possible to autocomplete a location search or display a list of suggestions just like Apple's Maps app? Thanks!
回答1:
Check this post: https://stackoverflow.com/a/20141677/1464327
Basically, you can make multiple requests. For exemple, when the user types, start a timer, when the timer finishes, make a request. Whenever the user types, cancel the previous timer.
Implement textField:shouldChangeCharactersInRange:replacementString:
of the text field delegate.
static NSTimer *_timer = nil;
[_timer invalidate];
_timer = [NSTimer timerWithTimeInterval:1.5 target:self selector:@selector(_search:) userInfo:nil repeats:NO];
Then implement the _search method to make the request.
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = self.textField.text;
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
// check for error and process the response
}];
I've never implemented something like this. I'm just telling what my starting point would be. Hopefully this will give you some direction.
来源:https://stackoverflow.com/questions/23166132/how-to-search-for-locations-using-uisearchbar-with-autocompletion-and-suggestion