简体   繁体   English

Yelp API 业务详细信息端点

[英]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.能够从业务匹配端点检索业务 ID 后,我现在尝试使用该业务 ID 将其汇集到业务详细信息端点。 I am just learning about calling APIs, so please bear with me.我只是在学习调用 API,所以请耐心等待。 Thank you!谢谢!

The following code is what allowed me to do the Business Match:以下代码允许我进行业务匹配:

Calling the API -->调用 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.我希望能够从任何业务匹配结果中自动提取该业务 ID。 The problem is in the following code.问题出在以下代码中。

Calling the API -->调用 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.通常,当您从网络中获取 JSON 数据时,您想要做的是将其序列化为您可以在 Swift 中使用的对象。 Fortunately, Swift has tools for easily converting json to objects and back again, namely the Codable protocol.幸运的是,Swift 有工具可以轻松地将 json 转换为对象,然后再转换回来,即Codable协议。 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.但本质上,这需要查看我们从服务器获得的响应并创建一个反映该响应的structclass So in your case the raw json returned from the server looks like:因此,在您的情况下,从服务器返回的原始 json 如下所示:

{
    "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.这是一个包含一个关键businesses的字典,它具有一组字典的值,其中包含描述业务的键值对。 With the JSON above there's only one element in the array.对于上面的 JSON,数组中只有一个元素。

So now that we know something about what the response looks like we can begin to create some structs that conform to Codable .所以现在我们对响应的样子有了一些了解,我们可以开始创建一些符合Codable结构。 We know we need one top-level struct with with a property businesses that is an array that contains structs describing each business.我们知道我们需要一个带有属性businesses顶级struct ,它是一个包含描述每个业务的结构的数组。

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

Next you create BusinessResponse .接下来创建BusinessResponse Now if all you care about is the id , you can just make BusinessResponse be:现在,如果您只关心id ,则可以将BusinessResponse设为:

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:与其将我们想要解码的 JSON 对象序列化为我们的BusinessesResponse结构,我们可以通过将switch语句更新为:

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.在此请求中,通过 URL 路径发送参数,即企业的 id。 So, path should be:所以, path应该是:

       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:因此task不再需要处理参数,应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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