Search code examples
iosswiftuisearchcontroller

UISearchController request to webservice without stacking many requests


I'm using the UISearchController to get objects to my tableview. My main problem is about stacking a lot of requests while the user types the text.

Every time the user type a character, the controller sends another request to my api and it does not make sense to me, because the first request will be for sure the longest one (if the user types "a", a lot of items is coming and the request will take a lot of time), and it will overwrite the short request.

  1. User types: a (first request will take 10seconds to take everything which contains a)

  2. User keep typing: bacate (a lot of request being faster then the first one)

  3. The API returns all the requests for bacate (fruit abacate) and will show in screen.

  4. The API NOW (because takes a lot of time) returns the request for the single a and overwrite with all fruits which contains a.

Sorry for the mess of my question, I'm really confused.


Solution

  • Well you can send the requests with delay and cancel the previous request. Here my example:

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    
        if searchText != "" {
            // to limit network activity, reload half a second after last key press.
            NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MyController.search), object: nil)
            self.perform(#selector(MyController.search), with: nil, afterDelay: 0.5)
        }
    }
    
    func search() {
    
        // Send request
    
    }