如何用重复的查询键构造URL?
How to construct URL with repeating query keys?
我必须构建这样的 URL "myapi?category=69&filters[[=18=]]=83,84&filters[[=19=]]=79"
我尝试首先使用 URLQueryItem 和 URLComponents
在 Playground 中构建
func callApi(categoryID: String, paramName: String, paramVal: String) {
let queryItems = [URLQueryItem(name: "category", value: categoryID), URLQueryItem(name: "filters[\(paramName)]", value: paramVal)]
var urlComps = URLComponents(string: "myapi")!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)
}
callApi(categoryID: "69", paramName: "pa_ram", paramVal: "84")
但我弄错了 URL "myapi?category=69&filters%5Bpa_ram%5D=84" 而且我也无法理解我应该如何构建 API重复查询键。如果有任何帮助,我将不胜感激。
为了支持多个过滤器,我会使用字典来将过滤器参数传递给函数
func callApi(categoryID: String, parameters: [String: String]) -> URL {
var queryItems = [URLQueryItem(name: "category", value: categoryID)]
for parameter in parameters {
queryItems.append(URLQueryItem(name: "filters[\(parameter.key)]", value: parameter.value))
}
var urlComps = URLComponents(string: "myapi")!
urlComps.queryItems = queryItems
return urlComps.url!
}
请注意,字典是无序的,因此如果顺序很重要,您可以改用自定义结构并传递它的数组。
要使用方括号,我只需搜索并替换 url 字符串
let url = callApi(categoryID: "69", parameters: ["pa_ram": "84", "pa_storage": "79"])
let fixed = url.absoluteString
.replacingOccurrences(of: "%5B", with: "[")
.replacingOccurrences(of: "%5D", with: "]")
我必须构建这样的 URL "myapi?category=69&filters[[=18=]]=83,84&filters[[=19=]]=79"
我尝试首先使用 URLQueryItem 和 URLComponents
在 Playground 中构建func callApi(categoryID: String, paramName: String, paramVal: String) {
let queryItems = [URLQueryItem(name: "category", value: categoryID), URLQueryItem(name: "filters[\(paramName)]", value: paramVal)]
var urlComps = URLComponents(string: "myapi")!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)
}
callApi(categoryID: "69", paramName: "pa_ram", paramVal: "84")
但我弄错了 URL "myapi?category=69&filters%5Bpa_ram%5D=84" 而且我也无法理解我应该如何构建 API重复查询键。如果有任何帮助,我将不胜感激。
为了支持多个过滤器,我会使用字典来将过滤器参数传递给函数
func callApi(categoryID: String, parameters: [String: String]) -> URL {
var queryItems = [URLQueryItem(name: "category", value: categoryID)]
for parameter in parameters {
queryItems.append(URLQueryItem(name: "filters[\(parameter.key)]", value: parameter.value))
}
var urlComps = URLComponents(string: "myapi")!
urlComps.queryItems = queryItems
return urlComps.url!
}
请注意,字典是无序的,因此如果顺序很重要,您可以改用自定义结构并传递它的数组。
要使用方括号,我只需搜索并替换 url 字符串
let url = callApi(categoryID: "69", parameters: ["pa_ram": "84", "pa_storage": "79"])
let fixed = url.absoluteString
.replacingOccurrences(of: "%5B", with: "[")
.replacingOccurrences(of: "%5D", with: "]")