简体   繁体   中英

Yelp API Business Details Endpoint

After being able to retrieve the Business ID from the Business Match endpoint, I am now trying to use that business ID to funnel it to the Business Details Endpoint. I am just learning about calling APIs, so please bear with me. Thank you!

The following code is what allowed me to do the Business Match:

Calling the API -->

import Foundation
import Moya


private let apiKey = ""


enum YelpService {
    enum BusinessMatch: TargetType {
        case match(name: String, address1: String, city: String, state: String, country: String)

        public var baseURL: URL { return NSURL(string: "https://api.yelp.com")! as URL
        }


        public var path: String {
            switch self {
            case .match:
                return "/v3/businesses/matches"
            }
        }

        var method: Moya.Method {
            return.get
        }

        var sampleData: Data {
            return Data()
        }

        var task: Task {
            switch self {
            case let .match(name, address1, city, state, country):
                return .requestParameters(parameters: ["name": name, "address1": address1, "city": city, "state": state, "country": country, "limit": 1], encoding: URLEncoding.queryString)
            }
        }

        var headers: [String : String]? {
            return ["Authorization": "Bearer \(apiKey)"]
        }
}
}

Returning the Business Match Endpoint -->

import UIKit
import CoreData
import Moya

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    let service = MoyaProvider<YelpService.BusinessMatch>()


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        service.request(.match(name: "Sushi Damo", address1:
            "330 W 58th St", city: "New York", state: "NY", country: "US")) { (result) in
                switch result {
                case .success(let response):
                    print(try? JSONSerialization.jsonObject(with: response.data, options: []))
                case .failure(let error):
                    print("Error: \(error)")
                }
        }
        return true
}




    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "APITest")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

After calling the Business Match Endpoint, I received the following information:

Optional({
    businesses =     (
                {
            alias = "sushi-damo-new-york";
            coordinates =             {
                latitude = "40.76778";
                longitude = "-73.98358";
            };
            "display_phone" = "(212) 707-8609";
            id = J85NKgA4tOgBAoqxu0vBNw;
            location =             {
                address1 = "330 W 58th St";
                address2 = "";
                address3 = "";
                city = "New York";
                country = US;
                "display_address" =                 (
                    "330 W 58th St",
                    "New York, NY 10019"
                );
                state = NY;
                "zip_code" = 10019;
            };
            name = "Sushi Damo";
            phone = "+12127078609";
        }
    );
})

I want to be able to pull out that Business ID automatically from any business match result. The problem is in the following code.

Calling the API -->

enum YelpDetails {
    enum BusinessDetail: TargetType {
        case BusinessID(id: String)

        public var baseURL: URL { return NSURL(string: "https://api.yelp.com")! as URL
        }

        public var path: String {
            switch self {
            case .BusinessID:
                return "https://api.yelp.com/v3/businesses/{id}"
            }
        }

        var method: Moya.Method {
            return.get
        }

        var sampleData: Data {
            return Data()
        }

        var task: Task {
            switch self {
            case let .BusinessID(id):
                return .requestParameters(parameters: ["BusinessID": id], encoding: URLEncoding.queryString)
            }
        }

        var headers: [String : String]? {
            return ["Authorization": "Bearer \(apiKey)"]
        }
    }
}

Returning the results from the Business Details Endpoint -->

   let information = MoyaProvider<YelpDetails.BusinessDetail>()

    func call(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        information.request(.BusinessID(id: "J85NKgA4tOgBAoqxu0vBNw")) {
            (result) in
            switch result {
            case .success(let response):
                print(try? JSONSerialization.jsonObject(with:
                    response.data, options: []))
            case .failure(let error):
                print("Error: \(error)")
            }
        }
        return true
}

Typically what you'll want to do when you get JSON data off the network is serialize it into objects that you can work with in Swift. Fortunately, Swift has tools for easily converting json to objects and back again, namely the Codable protocol. Check out this video for more information. But essentially what that entails is looking at the response we get from the server and creating a struct or class that mirrors that. So in your case the raw json returned from the server looks like:

{
    "businesses": [
        {
            "id": "J85NKgA4tOgBAoqxu0vBNw",
            "alias": "sushi-damo-new-york",
            "name": "Sushi Damo",
            "coordinates": {
                "latitude": 40.76778,
                "longitude": -73.98358
            },
            "location": {
                "address1": "330 W 58th St",
                "address2": "",
                "address3": "",
                "city": "New York",
                "zip_code": "10019",
                "country": "US",
                "state": "NY",
                "display_address": [
                    "330 W 58th St",
                    "New York, NY 10019"
                ]
            },
            "phone": "+12127078609",
            "display_phone": "(212) 707-8609"
        }
    ]
}

This is a dictionary with one key businesses which has a value of an array of dictionaries with key-value pairs describing a business. With the JSON above there's only one element in the array.

So now that we know something about what the response looks like we can begin to create some structs that conform to Codable . We know we need one top-level struct with with a property businesses that is an array that contains structs describing each business.

struct BusinessesResponse: Codable {
    let businesses: [BusinessResponse]
}

Next you create BusinessResponse . Now if all you care about is the id , you can just make BusinessResponse be:

struct BusinessResponse: Codable {
    let id: String
}

Then update how you respond here:

    service.request(.match(name: "Sushi Damo", address1:
            "330 W 58th St", city: "New York", state: "NY", country: "US")) { (result) in
                switch result {
                case .success(let response):
                    print(try? JSONSerialization.jsonObject(with: response.data, options: []))
                case .failure(let error):
                    print("Error: \(error)")
                }
        }

Rather than serialize a JSON object we want decode to our BusinessesResponse struct, which we can do by updating the switch statement to:

switch result {
case .success(let response):
    let businessesResponse = try? JSONDecoder().decode(BusinessesResponse.self, from: response.data)
    let firstID = businessesResponse?.businesses.first?.id
    // Do something with ID
case .failure(let error):
    print("Error: \(error)")
}

The next request I don't think will work as written. In this request the parameter, the id of the business, is sent via the path of the URL. So, path should be:

       public var path: String {
            switch self {
            case let .BusinessID(id):
                return "v3/businesses/\(id)"
            }
        }

And so task no longer needs to handle the parameter and should be:

        var task: Task {
            switch self {
            case .BusinessID:
                return .requestParameters(parameters:[:], encoding: URLEncoding.queryString)
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM