Displaying annotations on the map view

At this point, you have implemented MapViewController to manage the map view on the Map screen, and you can set the map region. You will now modify MapViewController to get an array of RestaurantItem instances from MapDataManager and add it to the map view. Remember that RestaurantItem conforms to the MKAnnotation protocol. When objects conforming to the MKAnnotation protocol are added to a map view, the view controller for the map view, MapViewController, is responsible for providing the necessary MKAnnotationView instances, which will appear as pins in the map view. Do the following steps:

  1. Click MapViewController.swift in the Project navigator and remove the boilerplate code.
  1. Just below the mapView property declaration, add the following:
let manager = MapDataManager()

This creates an instance of MapDataManager and assigns it to manager.

  1. Add the following method after viewDidLoad():
func addMap(_ annotations:[RestaurantItem]) {
mapView.setRegion(manager.currentRegion(latDelta: 0.5,
longDelta: 0.5), animated: true)
mapView.addAnnotations(manager.annotations)
}

This method takes a parameter, annotations, which is an array of RestaurantItem instances. It then sets the region of the map to be displayed in the map view using the currentRegion method of MapDataManager, then adds each RestaurantItem in the annotations array to the map view. The map view's delegate (MapViewController in this case) then automatically provides a pin for every RestaurantItem whose coordinates are visible on the screen.

  1. You need to have MapDataManager fetch the annotations array, so add the following method above the addMap(_:) method:
func initialize() {
manager.fetch { (annotations) in
addMap(annotations)
}
}

This calls the fetch() method in MapDataManager that you implemented earlier, which loads MapLocations.plist and creates and assigns the array of RestaurantItem instances to annotations.

  1. Add initialize() inside viewDidLoad() so it will be called when the map view is loaded:
override func viewDidLoad() {
super.viewDidLoad()
initialize()
}

Build and run the application. You should see the following on the Map screen:

You now have pins showing restaurant locations on your map, but you need to update your code to use custom pins that look like the ones in the app tour. You will do that in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.32.222