问题
I would like to add autocomplete feature to my app. My idea is to use autocompleteQuery:bounds:filter:callback from GMSPlacesClient class. While user is typing, I would like to call that method, but I guess if I send several requests, I could receive responses out of order. For that reason I would like to cancel the current one, but I don't see a way. Maybe it is implemented internally, I don't know. Any help or suggestion? Thanks a lot.
I realised responses could come out of order. I created a small sample with a textfield and one table. I sent a request every time user taps a letter and the results say that there is no automatic request cancelation or order.
2015-11-13 15:16:14.668 TestGooglePlaces[5233:60b] u
2015-11-13 15:16:15.550 TestGooglePlaces[5233:60b] ut
2015-11-13 15:16:15.700 TestGooglePlaces[5233:60b] uto
2015-11-13 15:16:15.967 TestGooglePlaces[5233:60b] utop
2015-11-13 15:16:16.552 TestGooglePlaces[5233:60b] utopi
2015-11-13 15:16:23.035 TestGooglePlaces[5233:60b] Results for u
2015-11-13 15:16:23.079 TestGooglePlaces[5233:60b] Results for utop
2015-11-13 15:16:23.087 TestGooglePlaces[5233:60b] Results for utopi
2015-11-13 15:16:23.093 TestGooglePlaces[5233:60b] Results for ut
2015-11-13 15:16:23.155 TestGooglePlaces[5233:60b] Results for uto
How can I fix that problem? The only idea I have is to use the REST web service and cancel the ongoing requests manually.
回答1:
We on the Places API for iOS team are aware of this problem and are working on it. In the next release of the SDK we'll have a class which takes care of managing these requests and returning them in the correct order.
In the meantime, you can manage these requests by keeping track of the order that the requests came in and ignoring responses if they're too old:
@implementation YourClass {
NSUInteger _sequenceNumber;
__block NSUInteger _mostRecentResponseNumber;
}
- (void)autocompleteQuery:(NSString *)query {
NSUInteger thisSequenceNumber = ++_sequenceNumber;
[_placesClient autocompleteQuery:query
bounds:nil
filter:nil
callback:^(NSArray * _Nullable results, NSError * _Nullable error) {
if (thisSequenceNumber <= _mostRecentResponseNumber) {
return;
}
_mostRecentResponseNumber = thisSequenceNumber;
// process results here
}];
}
Not the nicest, but it should work until we release a better way of doing this :)
来源:https://stackoverflow.com/questions/33692599/how-can-i-cancel-an-ongoing-request-in-gmsplacesclient-autocompletequery