- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在能够从业务匹配端点检索业务 ID 后,我现在尝试使用该业务 ID 将其汇集到业务详细信息端点。我只是在学习如何调用 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)"]
}
}
}
返回业务匹配端点 -->
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)")
}
}
}
}
调用Business Match Endpoint后,我收到了以下信息:
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";
}
);
})
我希望能够从任何业务匹配结果中自动提取该业务 ID。问题出在下面的代码中。
调用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)"]
}
}
}
从 Business Details 端点返回结果 -->
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
}
最佳答案
通常,当您从网络获取 JSON 数据时,您需要做的是将其序列化为您可以在 Swift 中使用的对象。幸运的是,Swift 有工具可以轻松地将 json 转换为对象,然后再转换回对象,即 Codable
协议(protocol)。查看this video了解更多信息。但本质上,这需要查看我们从服务器获得的响应,并创建一个反射(reflect)该响应的 struct
或 class
。所以在你的情况下,从服务器返回的原始 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"
}
]
}
这是一个带有一个键 businesses
的字典,它的值是一个字典数组,键值对描述一个企业。对于上面的 JSON,数组中只有一个元素。
现在我们已经了解了响应的内容,我们可以开始创建一些符合 Codable
的结构。我们知道我们需要一个顶级 struct
,它具有属性 businesses
,这是一个包含描述每个业务的结构的数组。
struct BusinessesResponse: Codable {
let businesses: [BusinessResponse]
}
接下来创建 BusinessResponse
。现在,如果您只关心 id
,您可以将 BusinessResponse
设为:
struct BusinessResponse: Codable {
let id: String
}
然后在此处更新您的回复方式:
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)")
}
}
我们不想序列化一个 JSON 对象,而是将其解码为我们的 BusinessResponse
结构,我们可以通过将 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)")
}
我认为下一个请求不会像写的那样工作。在此请求中,参数(业务 ID)通过 URL 路径发送。所以,path
应该是:
public var path: String {
switch self {
case let .BusinessID(id):
return "v3/businesses/\(id)"
}
}
所以 task
不再需要处理参数,应该是:
var task: Task {
switch self {
case .BusinessID:
return .requestParameters(parameters:[:], encoding: URLEncoding.queryString)
}
}
关于ios - Yelp API 业务详情端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230755/
我正在使用 yelp api,我能够在 api 的帮助下检索产品评论。 但是,是否也可以使用 Yelp API 发表评论? 我需要从我自己的 php 脚本发布对产品的评论。 最佳答案 不,Yelp A
我知道我们可以使用 Yelp 评论搜索 API 搜索 Yelp 上发布的评论。是否可以使用 Yelp API 发布评论? 最佳答案 我尝试使用 Yelp API 来执行此操作,但当时不受支持。刚刚检查
我的 yelp 按钮的 html 代码是: Check out CurveSetter Tutoring on Yelp(function(d, t) {var g = d.createElement
我意识到 Yelp.com 会在鼠标移动或发生某些事情(单击元素)时进行某种跟踪。这是怎么回事?有图书馆吗?如何在不对性能造成几乎为零的影响的情况下做到这一点? 您可以在下面的 Firebug 中看到
我尝试从 Yelp 数据集挑战网站 (https://www.yelp.com/dataset_challenge) 打开文件。我已经成功做到了,但是,我无法打开文件,因为它没有扩展名。它大约是 4
我正在阅读 API 并单击业务 API 并找到 reviews作为可能的回应。描述中写道, List of up to 1 review snippet for the business 这是否意味着
这个问题在这里已经有了答案: Extracting an attribute value with beautifulsoup (10 个回答) 去年关闭。 从事网络抓取项目以建立我的知识(初学者)。
Yelp 是否提供 API 支持在企业页面上撰写评论?有没有办法从其他网站撰写评论? 最佳答案 不,而且不太可能会有。 全面披露:我在 Yelp 工作了 2 年多。 关于php - Yelp API
在查看了多篇在线文章、StackOverflow 和 Yelp Google Group 后,我无法找出 Yelp API 请求产生的无效签名错误的问题。 这是确切的错误: {'error': {'t
我正在尝试将 Yelp 的 API 与纬度/经度位置结合使用。我使用了 yelp 给出的 javascript 代码,它基本上有一个参数数组,并像这样将值插入其中: parameters.push([
我不知道如何将 target="_blank"属性添加到 5 星评级徽章。 这是我插入网页的内容...来自 yelp。我将最后一行添加到脚本中以尝试添加属性,但它不会接受。我可以,但是让它接受之前的
我正在尝试复制 yelp.com 上的星级评分小部件 - 5 星评分小部件,当您将鼠标悬停在下一颗星上时,所有之前的星星都会改变颜色以匹配活跃的星星。还需要一个显示星级描述的悬停状态。 您可以在此处查
我正在向 yelp api 发送请求以搜索提供纬度和经度的地点,但它给了我以下错误 error = { description = "Invalid signature. Ex
我正在使用 Yelp API,这是搜索方法: func searchWithTerm(term: String, success: (AFHTTPRequestOperation!, AnyObjec
在能够从业务匹配端点检索业务 ID 后,我现在尝试使用该业务 ID 将其汇集到业务详细信息端点。我只是在学习如何调用 API,所以请多多包涵。谢谢! 以下代码使我能够进行业务匹配: 调用API -->
我正在使用 Yelp API 调用业务匹配端点。不幸的是,我遇到了一个我已经玩了一段时间的错误,但似乎找不到它返回以下响应的原因: Optional({ error = {
我一直在尝试从使用 Firefox 时出现(最清晰)的 Yelp 站点徽章中移除底部边框。 div.yelp-biz-badge-script-plain-j3i0uapgqgIpKNS9KA2v4
我正在使用 Business Search Yelp Fusion Api 中的功能。 为什么我似乎无法获取所有业务? 这是一个例子: 当我发出这个请求时,它返回前 20 个结果和 485 的总属性。
我正在尝试使用 Yelp API2 做一些事情 $response = json_decode($data); 它以 PHP 对象格式返回数据,如下所示: stdClass Object ( [reg
我正在连接到 yelp 2.0 Api,我想知道是否有办法检索类别和子类别的列表。我知道该列表可在此处获得 http://www.yelp.com/developers/documentation/c
我是一名优秀的程序员,十分优秀!