Creating MapDataManager

As you have done in previous chapters, you'll create a data manager class, MapDataManager, that will load restaurant data from Maplocations.plist and put the data into RestaurantItem instances. Perform the following steps:

  1. Right-click on the Model folder inside the Map folder and select New File.
  2. iOS should already be selected. Choose Swift File and then click Next.
  3. Name this file MapDataManager. Click Create.
  4. Add the following under the import statement to declare the MapDataManager class:
class MapDataManager {

}
  1. Add the following properties between the curly braces:
fileprivate var items:[RestaurantItem] = []

var annotations:[RestaurantItem] {
return items
}

The items array will contain RestaurantItem instances. fileprivate makes the items array only accessible inside the MapDataManager class, and annotations is a computed property that returns a copy of items when accessed.

  1. Add the following methods after the property declarations:
func fetch(completion:(_ annotations:[RestaurantItem]) -> ()){
if items.count > 0 { items.removeAll() }
for data in loadData() {
items.append(RestaurantItem(dict: data))
}
completion(items)
}

fileprivate func loadData() -> [[String:AnyObject]] {
guard let path = Bundle.main.path(forResource:
"MapLocations", ofType: "plist"),
let items = NSArray(contentsOfFile: path) else {
return [[:]]
}
return items as! [[String:AnyObject]]
}

The fetch() and loadData() methods work the same way as those in ExploreDataManager. However, the fetch() method here has a completion closure as a parameter, which looks like this:

completion:(_ annotations:[RestaurantItem]) -> ()

Sometimes, you don't know when an operation will be finished. For example, you need to do an action after you've downloaded a file from the internet, but you don't know how long it would take to download. The completion closure here, in effect, is saying when all of the data from the .plist file has been processed, return the annotations array. The annotations array will later be used when adding RestaurantItem instances to the Map screen.

Now consider the MapLocations.plist file once more:

This file has the same structure as ExploreData.plist. The Root item is an array and contains dictionary items. Since both ExploreData.plist and MapLocations.plist have an array of dictionary objects, it would be more efficient if you could create a single method that will load .plist files and use it wherever it was needed. You will do this 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
3.141.199.56