TL DR
Project example: https://github.com/JakubMazur/SO40539590
Ok, so for starters, I suggest you separate data from your controller code. I choose json format as the most universal. So:
[ { "title":"Litzman Bar", "subtitle":"נמל תל אביב 18,תל אביב", "coordinates":{ "lat":32.100668, "lon":34.775192 } }, { "title":"Shalvata", "subtitle":"האנגר 28,נמל תל אביב", "coordinates":{ "lat":32.101145, "lon":34.775163 } }, { "title":"Markid", "subtitle":"אבן גבירול 30,תל אביב", "coordinates":{ "lat":32.074961, "lon":34.781679 } } ]
This is basically your database.
Now consider it in Array for use inside your ViewConttroller . Again, I suggest you break it down into model objects such as Location and Coordinate . Let's look at one class of this example:
class Location: NSObject { var title : String = String() var subtitle : String = String() var coordinates : Coordinate = Coordinate() public class func locationFromDictionary(_ dictionary : Dictionary<String, AnyObject>) -> Location { let location : Location = Location() location.title = dictionary["title"] as! String location.subtitle = dictionary["subtitle"] as! String location.coordinates = Coordinate.coordinateFromDictionary(dictionary["coordinates"] as! Dictionary<String, AnyObject>) return location; } }
I will not embed code to parse the json file on these objects, because this is not a question. You will find in the repository.
And now let's focus on the question.
I recommend that you do not look for annotations, but look for your data model and redraw annotations if necessary
To do this (I will use the UISearchBar for it):
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.displayArray = self.locationsDatabase.filter() { return $0.title.contains("i") }
Then, when you set the setter as follows:
var displayArray : Array<Location> = [] { didSet { self.mapView .removeAnnotations(self.mapView.annotations) for location in displayArray { let coords : Coordinate = location.coordinates let point = MKPointAnnotation() point.coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(coords.latitude),CLLocationDegrees(coords.longitude)) point.title = location.title point.subtitle = location.subtitle mapView.addAnnotation(point) } } }
You can redraw your annotations. Extreme cases, such as an empty search field, case sensitivity, keyboard rejection, I leave to you. But hope you get a general idea. You might think that it is reconfigured, but with objects as separate classes and a universal format as data input, it may come in handy in the future.
Full project: https://github.com/JakubMazur/SO40539590