将更多数据附加到公共类中定义的api

问题描述 投票:1回答:2

我正在打电话给像这样的网络服务......

WebServiceClient.shared.getNearbyLocationsList(with.....

这反过来调用另一个类似的..

func getNearbyLocationsList(withParameters parameters: APIParameters, completionHandler: @escaping (Bool, [String: Any]?) -> Void) {
    guard let url = APIClient.shared.createWebServiceUrl(forPath: WebServicePath.googleLocationsApi, withParameters: .....

在这里,这部分WebServicePath.googleLocationsApi..将这个变量称为另一个类......

static let googleLocationsApi = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
let googleKey = "YOUR GOOGLE KEY"

所以这将是api网址。但我的实际位置网址看起来像这样......

https://maps.googleapis.com/maps/api/place/nearbysearch/json?sensor=true&location=10.123456,78.910111&radius=1000&key=googleKey

因此,这整个部分必须附加上面给出的static let googleLocationsApi =....网址:

?sensor=true&location=10.123456,78.910111&radius=1000&key=Aqporjp9asdjhg425jhgjhgvbjhAJGFKJfkjgkj4kjakjfb

这里,位置,半径和键在其他地方定义。那么我怎么能有一个api结构来获取这些值,从而得到最终的api ..?

ios swift
2个回答
2
投票

@Aks,你的回答是对的,我通过添加一个函数做了一些改变,你可以通过它来传递你的动态参数。

 let googleKey = "YOUR GOOGLE KEY"
 var urlComponents = URLComponents(string: googleLocationsApi)!
 urlComponents.queryItems = appendQueryItems(queryItems: ["sensor": true,"radius":1000, "location": "10.123456,78.910111", "key": googleKey])

 debugPrint(urlComponents.url!)

功能定义

func appendQueryItems(queryItems: [String: Any]) -> [URLQueryItem] {

    var urlQueryItems = [URLQueryItem]()
    for (key,value) in queryItems {
        urlQueryItems.append(URLQueryItem(name: "\(key)", value: "\(value)"))
    }

    return urlQueryItems
}

0
投票

您可以使用URLComponent对URL中的查询参数进行编码。例:-

var urlComponents = URLComponents(string: googleLocationsApi)!
urlComponents.queryItems = [
    URLQueryItem(name: "sensor", value: true),
    URLQueryItem(name: "location", value: "10.123456,78.910111")
]
urlComponents.url      // this should give you the url you expect.

有关详细信息,请访问: - https://www.swiftbysundell.com/posts/constructing-urls-in-swift这是John Sundell的一篇精彩文章,详细解释了它

© www.soinside.com 2019 - 2024. All rights reserved.