GMSPlacesClient Cancellation Request

In one of my applications, users have the ability to search for a location by its name. I use the Google Maps API to display auto-complete offers with GMSPlacesClient.

Below is the code below:

func performSearch() {
        let filter = GMSAutocompleteFilter()
        filter.type = GMSPlacesAutocompleteTypeFilter.City
        placesClient?.autocompleteQuery(searchBar.text!, bounds: nil, filter: filter, callback: { (results, error: NSError?) -> Void in
            // update results
        })
    }

This code works very well. However, I noticed one scenario in which it fails. For example, if I'm looking for Chicago. If I type “Ch” very quickly, sometimes the results are returned for “Ch” correctly, but sometimes I get results for “C”. The problem arises from the fact that these are asynchronous requests, and I do a search every time the user enters something. So, although the request "C" was initiated before the "Ch", it may return last.

Therefore, I must cancel all previous initiated requests before I start a new one. However, I could not find a way to do this. Does anyone know how to achieve it?

Update

I tried using a workaround:

    let string = myResults[0].attributedFullText
    string.enumerateAttribute(kGMSAutocompleteMatchAttribute, inRange: NSMakeRange(0, string.length), options: .Reverse) { (value, range, stop) -> Void in
        if value != nil {
            let t = NSString(string: string.string)
            let str = t.substringWithRange(range)
            //now compare with original search string
        }
    }

This fixes the problem with Chicago (and other similar cases). However, this approach will disable autocomplete suggestions when the user makes a typo, because the matching string and the original search string are always different in this case.

So the question remains open. The ideal approach is to cancel all previously initiated requests. If Google also retained the original search string, then an approach similar to the one presented above might work, but it looks like the original search string is not returned after the query ...

, - SDK, Alamofire . . , ...

+4

Source: https://habr.com/ru/post/1615272/


All Articles