Creating RestaurantAPIManager

You have learned how to create a data manager class to load data from a .plist file in earlier chapters. Loading data from JSON files will be similar. You will now create RestaurantAPIManager, a data manager class that loads data from JSON files that you have just added to your project.


You can learn more about JSONSerialization at https://developer.apple.com/documentation/foundation/jsonserialization.

Perform the following steps:

  1. Right-click on the Misc folder and choose New File.
  2. iOS should already be selected. Choose Swift File and then click Next.
  3. Name this file RestaurantAPIManager. Click Create.
  4. Add the following under the import statement to declare the RestaurantAPIManager structure:
struct RestaurantAPIManager {

}
  1. Implement the loadJSON(file:) method between the curly braces. This method takes the filename of a JSON file and returns an array of dictionaries containing the file data:
static func loadJSON(file name:String) -> [[String:AnyObject]]{
var items = [[String:AnyObject]]()
guard let path = Bundle.main.path(forResource: name,
ofType: "json"),let data = NSData(contentsOfFile: path) else {
return [[:]]
}

do {
let json = try JSONSerialization.jsonObject(with: data as
Data, options: .allowFragments) as AnyObject
if let restaurants = json as? [[String:AnyObject]] {
items = restaurants as [[String:AnyObject]]
}
}
catch {
print("error serializing JSON: (error)")
items = [[:]]
}
return items
}

Let's see how this method works:

  • static func loadJSON(file name:String) -> [[String:AnyObject]]
    The static keyword indicates that this is a type method. Type methods are called on the type, and not on instances of the type. The method, loadJSON(file:), takes a string, name, as a parameter and returns an array of dictionaries.
  • var items = [[String:AnyObject]]() 
    The items variable is assigned an empty array of dictionaries.
  • static func loadJSON(file name:String) -> [[String:AnyObject]]
    This line looks for the file named name in the application bundle, and if found, loads the file into an NSData object, data. If the file is not found, an empty array of dictionaries is returned.
  • do {
    let json = try JSONSerialization.jsonObject(with: data as Data, options:
    .allowFragments) as AnyObject
    if let restaurants = json as? [[String:AnyObject]] {
    items = restaurants as [[String:AnyObject]]
    }
    }
    catch {
    print("error serializing JSON: (error)")
    items = [[:]]
    }
    This part uses the do-catch block that you learned about in Chapter 8, Protocols, Extensions, and Error Handling. JSONSerialization.jsonObject(with:options:) tries to parse the JSON file and assigns it to a constant, json. The next line tries to cast json as an array of dictionaries, and if successful, assigns it to items. Otherwise, an error message is written to the Debug area and an empty array of dictionaries is assigned to items.
  • return items
    If all goes well,
    items is returned as an array of dictionary objects containing restaurant data.

RestaurantAPIManager has been created, but before you can use it, you'll need to modify your project quite a bit. Let's see what's required to display restaurant information in the Restaurant List and Map screens next.

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

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