Search code examples
iosswiftgrand-central-dispatchdispatch

GCD terminate request


I would like to send a request to server after a delay, but if user has changed state of UITextFiled this request should be terminated. What I have now is

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {  
    sessionManager.session.invalidateAndCancel()
    APIModel().searchRequest()...
}

but it actually does not stop the request from getting to server. I guess I should use GDC delay to wait a second before sending request and then, if UITextField changed, terminate it. But I could not find an example of this logic realisation.


Solution

  • You can't "terminate" a request.

    You can create an object with a "cancelled" property. Then you dispatch code that access that object, and which at appropriate times checks whether the "cancelled" property is true. And from the outside, you set cancelled to true when you feel like it.

    If the operation manages to finish and detects that it was cancelled, it should then not produce any error message, and not do anything else, since it was cancelled.