gpt4 book ai didi

ios - 如何在 Moya 中添加参数?

转载 作者:行者123 更新时间:2023-12-01 16:06:01 24 4
gpt4 key购买 nike

所以我一直在通过 Gary Tokman 编写本教程构建一个餐厅查看应用程序,它很棒。从头到尾,一切都运行良好。

目的是更改或添加参数并包括“术语”或“类别”。现在,这会将搜索更改为特定业务,而不仅仅是餐馆。

这就是我卡住的地方
我似乎找不到执行此参数的正确语法。

这是 Business Endpoint 文档:https://www.yelp.com/developers/documentation/v3/business_search

这些是 swift 文件的代码

网络服务文件

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)"]
}

}

应用委托(delegate)文件
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)
}
}

有什么我遗漏或需要添加/更改的吗?

最佳答案

欢迎来到 Stackoverflow!

首先,试着回去研究那个网络库莫亚 .以下是其用法示例:
https://github.com/Moya/Moya/tree/master/docs/Examples

所以基本上你的问题是如何在 Moya 中添加参数?

嗯,这很容易,特别是如果你很好地掌握了使用 Moya。

让我们添加参数term .我会让你添加其他参数categories在这个答案之后你自己。

在您的枚举中 BusinessProvider ,有一个案例search , 正确的?您已经可以看到两个现有参数,为什么不添加一个名为 term 的新参数? ?

case search(lat: Double, long: Double, term: String)

由于您要在 task 中添加参数,不在 path 中, 那么我们去 task多变的。请记住,您可以在 task 中添加参数但在`task 中这样做更实际。

让我们在 中添加新参数搜索任务
case let .search(lat, long, term):
return .requestParameters(
parameters: [ "latitude": lat, "longitude": long, "term": term, "limit": 30], encoding: URLEncoding.queryString)

瞧!您现在有一个新的 term您的 search 中的参数案子。

关于ios - 如何在 Moya 中添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com