我正在打电话给像这样的网络服务......
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 ..?
@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
}
您可以使用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的一篇精彩文章,详细解释了它