[英]How to add parameters in Moya?
So I've been working on this tutorial by Gary Tokman to build a restaurant viewing app and it's great.所以我一直在编写Gary Tokman 的这个教程来构建一个餐厅查看应用程序,它很棒。 From the beginning to the end, everything works properly and well.
从开始到结束,一切正常。
The aim is to change or add a parameters and include either 'term' or 'categories'.目的是更改或添加参数并包括“术语”或“类别”。 This will then now change the search to a specific business than just restaurants.
这将现在将搜索更改为特定的业务,而不仅仅是餐馆。
This is where I'm stuck I cannot seem to find the proper syntax to execute this parameter.这就是我卡住的地方,我似乎找不到执行此参数的正确语法。
This is Business Endpoint the documentation: https://www.yelp.com/developers/documentation/v3/business_search这是 Business Endpoint 的文档: https : //www.yelp.com/developers/documentation/v3/business_search
These are the code for the swift file这些是 swift 文件的代码
Network Service File网络服务文件
import Foundation
import Moya
enum YelpService {
enum BusinessesProvider: TargetType {
case search(lat: Double, long: Double)
case details(id: String)
var baseURL: URL {
return URL(string: "https://api.yelp.com/v3/businesses")!
}
var path: String {
switch self {
case .search:
return "/search"
case let .details(id):
return "/\(id)"
}
}
var method: Moya.Method {
return .get
}
var sampleData: Data {
return Data()
}
var task: Task {
switch self {
case let .search(lat, long):
return .requestParameters(
parameters: [ "latitude": lat, "longitude": long, "limit": 30], encoding: URLEncoding.queryString)
case .details:
return .requestPlain
}
}
var headers: [String : String]? {
return ["Authorization": "Bearer \(apiKey)"]
}
}
AppDelegate File应用程序委托文件
import UIKit
import Moya
import CoreLocation
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
let window = UIWindow()
let locationService = LocationService()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let service = MoyaProvider<YelpService.BusinessesProvider>()
let jsonDecoder = JSONDecoder()
var navigationController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
locationService.didChangeStatus = { [weak self] success in
if success {
self?.locationService.getLocation()
}
}
locationService.newLocation = { [weak self] result in
switch result {
case .success(let location):
self?.loadBusinesses(with: location.coordinate)
case .failure(let error):
assertionFailure("Error getting the users location \(error)")
}
}
switch locationService.status {
case .notDetermined, .denied, .restricted:
let locationViewController = storyboard.instantiateViewController(withIdentifier:
"LocationViewController")
as? LocationViewController
locationViewController?.delegate = self
window.rootViewController = locationViewController
default:
let nav = storyboard
.instantiateViewController(withIdentifier: "StoreNavigationController") as? UINavigationController
self.navigationController = nav
window.rootViewController = nav
locationService.getLocation()
(nav?.topViewController as? StoreTableViewController)?.delegate = self
}
window.makeKeyAndVisible()
return true
}
private func loadDetails(for viewController: UIViewController, withId id: String) {
service.request(.details(id: id)) { [weak self] (result) in
switch result {
case .success(let response):
guard let strongSelf = self else { return }
if let details = try? strongSelf.jsonDecoder.decode(Details.self, from: response.data) {
let detailsViewModel = DetailsViewModel(details: details)
(viewController as? DetailsStoreViewController)?.viewModel = detailsViewModel
}
case .failure(let error):
print("Failed to get details \(error)")
}
}
}
private func loadBusinesses(with coordinate: CLLocationCoordinate2D) {
service.request(.search(lat: coordinate.latitude, long: coordinate.longitude)) { [weak self] (result) in
guard let strongSelf = self else { return }
switch result {
case .success(let response):
let root = try? strongSelf.jsonDecoder.decode(Root.self, from: response.data)
let viewModels = root?.businesses
.compactMap(StoreListViewModel.init)
.sorted(by: { $0.distance < $1.distance})
if let nav = strongSelf.window.rootViewController as? UINavigationController,
let storeListViewController = nav.topViewController as? StoreTableViewController {
storeListViewController.viewModels = viewModels ?? []
} else if let nav = strongSelf.storyboard
.instantiateViewController(withIdentifier: "StoreNavigationController") as?
UINavigationController {
strongSelf.navigationController = nav
strongSelf.window.rootViewController?.present(nav, animated: true) {
(nav.topViewController as? StoreTableViewController)?.delegate = self
(nav.topViewController as? StoreTableViewController)?.viewModels = viewModels ?? []
}
}
case .failure(let error):
print("Error: \(error)")
}
}
}
}
extension AppDelegate: LocationActions, ListActions {
func didTapAllow() {
locationService.requestLocationAuthorization()
}
func didTapCell(_ viewController: UIViewController, viewModel: StoreListViewModel) {
loadDetails(for: viewController, withId: viewModel.id)
}
}
Is there anything I'm missing or need to add/change?有什么我遗漏或需要添加/更改的吗?
Welcome to Stackoverflow!欢迎使用 Stackoverflow!
First off, try going back to studying that networking library Moya .首先,尝试回去研究那个网络库Moya 。 Here are the examples of its usage: https://github.com/Moya/Moya/tree/master/docs/Examples
下面是它的用法示例: https : //github.com/Moya/Moya/tree/master/docs/Examples
So basically your question is how to add parameters in Moya?所以基本上你的问题是如何在Moya中添加参数?
Well that's quite easy, especially if you have a good grasp of using Moya.嗯,这很容易,特别是如果您很好地掌握了使用 Moya。
Let's add the parameter term
.让我们添加参数
term
。 I will let you add the other parameter categories
by yourself after this answer.我会让你在这个答案之后自己添加其他参数
categories
。
In your enum BusinessProvider
, there's a case search
, right?在您的 enum
BusinessProvider
,有一个 case search
,对吗? And you already can see two existing parameters, why don't we add a new param called term
?而且您已经可以看到两个现有参数,为什么我们不添加一个名为
term
的新参数?
case search(lat: Double, long: Double, term: String)
Since you are adding the parameter in your task
, not in path
, then let's go to the task
variable.由于您是在
task
中添加参数,而不是在path
,那么让我们转到task
变量。 Remember you can add the params in the task
but its more practical to do it in the `task.请记住,您可以在
task
添加参数,但在 `task.
Let's add the new param in the search task让我们在搜索任务中添加新参数
case let .search(lat, long, term):
return .requestParameters(
parameters: [ "latitude": lat, "longitude": long, "term": term, "limit": 30], encoding: URLEncoding.queryString)
Voila!瞧! You now have a new
term
param in your search
case.您现在在
search
案例中有一个新的term
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.