簡體   English   中英

如何在Moya中添加參數?

[英]How to add parameters in Moya?

所以我一直在編寫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)"]
    }

}

應用程序委托文件

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!

首先,嘗試回去研究那個網絡庫Moya 下面是它的用法示例: https : //github.com/Moya/Moya/tree/master/docs/Examples


所以基本上你的問題是如何在Moya中添加參數?

嗯,這很容易,特別是如果您很好地掌握了使用 Moya。

讓我們添加參數term 我會讓你在這個答案之后自己添加其他參數categories

在您的 enum BusinessProvider ,有一個 case 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)

瞧! 您現在在search案例中有一個新的term參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM