I have a function to check the spelling of a city, if the name of the city is correct, I write its data to an object of class MarkerData.

func searchCity(city : String, marker : MarkerData) { let searchRequest = MKLocalSearchRequest() searchRequest.naturalLanguageQuery = city let activeSearch = MKLocalSearch(request: searchRequest) activeSearch.start { (response , error) in UIApplication.shared.endIgnoringInteractionEvents() if response != nil { let latitude = response?.boundingRegion.center.latitude let longitude = response?.boundingRegion.center.longitude let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude!, longitude!) marker.setTitle(value: "----") marker.setName(value: city) marker.setCoordinate(value: coordinate) marker.setAlive(value: true) } else { marker.setAlive(value: false) } } } 

It checks everything is fine, but when a request is made for checking, it takes some time, but the code does not wait for a response and goes on. It is crucial for me that the code does not go further until an answer is received. What are the solutions

    1 answer 1

    All right, start () is an asynchronous function with the completion handler , it is executed when the search ends. Firstly, the documentation says that you should call it only once, that is, if one search is started, launching a second time will cause unpredictable behavior or crash. I would bring activeSearch to a class variable, and call cancel () if the previous search is not over (this is a QA case, but it’s better to think about it immediately).

    Now at the core of the question: place the call to the continuation function in the completion handler , so that will have a synchronous call after the search. Do not forget to protect against memory leak, before (response, error) add [weak self] , and then call self? .ContinueMyProgramExecution (city, coordinate) .