如何构建一个 URL,其查询参数包含 Swift 中同一键的多个值?
How can I build a URL with query parameters containing multiple values for the same key in Swift?
我在我的 iOS 应用程序中使用 AFNetworking,对于它发出的所有 GET 请求,我从基础 URL 构建 url,然后使用 NSDictionary 键添加参数-值对。
问题是不同的值需要相同的密钥。
这是我需要最终 URL 看起来像的示例 -
http://example.com/.....&id=21212&id=21212&id=33232
在 NSDictionary 中不可能在相同的键中有不同的值。所以我尝试了 NSSet 但没有成功。
let productIDSet: Set = [prodIDArray]
let paramDict = NSMutableDictionary()
paramDict.setObject(productIDSet, forKey: "id")
我想你只需要做这样的事情:
let params = ["id" : [1, 2, 3, 4], ...];
这将被编码成:
....id%5B%5D=1&id%5B%5D=2&id%5B%5D=3&id%5B%5D=4....
您只需要 URLComponents
(或 Obj-C 中的 NSURLComponents)。基本思想是为您的 ID 创建一堆查询项。您可以将以下代码粘贴到 playground 中:
import Foundation
import XCPlayground
let queryItems = [URLQueryItem(name: "id", value: "1"), URLQueryItem(name: "id", value: "2")]
var urlComps = URLComponents(string: "www.apple.com/help")!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)
您应该会看到
的输出
www.apple.com/help?id=1&id=2
func queryString(_ value: String, params: [String: String]) -> String? {
var components = URLComponents(string: value)
components?.queryItems = params.map { element in URLQueryItem(name: element.key, value: element.value) }
return components?.url?.absoluteString
}
方法一
它可以将 QueryItem 添加到您现有的 URL。
extension URL {
func appending(_ queryItem: String, value: String?) -> URL {
guard var urlComponents = URLComponents(string: absoluteString) else { return absoluteURL }
// Create array of existing query items
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
// Create query item
let queryItem = URLQueryItem(name: queryItem, value: value)
// Append the new query item in the existing query items array
queryItems.append(queryItem)
// Append updated query items array in the url component object
urlComponents.queryItems = queryItems
// Returns the url from new url components
return urlComponents.url!
}
}
使用方法
var url = URL(string: "https://www.example.com")!
let finalURL = url.appending("test", value: "123")
.appending("test2", value: nil)
方法二
在此方法中,URL 将自动更新。
extension URL {
mutating func appendQueryItem(name: String, value: String?) {
guard var urlComponents = URLComponents(string: absoluteString) else { return }
// Create array of existing query items
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
// Create query item
let queryItem = URLQueryItem(name: name, value: value)
// Append the new query item in the existing query items array
queryItems.append(queryItem)
// Append updated query items array in the url component object
urlComponents.queryItems = queryItems
// Returns the url from new url components
self = urlComponents.url!
}
}
// How to use
var url = URL(string: "https://www.example.com")!
url.appendQueryItem(name: "name", value: "bhuvan")
用于附加查询项的 URL 扩展,类似于 Bhuvan Bhatt 的想法,但具有不同的签名:
- 它可以检测故障(通过返回
nil
而不是 self
),因此允许自定义处理 URL 不符合 RFC 3986 的情况。
- 它允许 nil 值,实际上将任何查询项作为参数传递。
- 为了性能,它允许一次传递多个查询项。
extension URL {
/// Returns a new URL by adding the query items, or nil if the URL doesn't support it.
/// URL must conform to RFC 3986.
func appending(_ queryItems: [URLQueryItem]) -> URL? {
guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
// URL is not conforming to RFC 3986 (maybe it is only conforming to RFC 1808, RFC 1738, and RFC 2732)
return nil
}
// append the query items to the existing ones
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems
// return the url from new url components
return urlComponents.url
}
}
用法
let url = URL(string: "https://example.com/...")!
let queryItems = [URLQueryItem(name: "id", value: nil),
URLQueryItem(name: "id", value: "22"),
URLQueryItem(name: "id", value: "33")]
let newUrl = url.appending(queryItems)!
print(newUrl)
输出:
在Swift中用多个参数形成URL
func rateConversionURL(with array: [String]) -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "example.com"
components.path = "/hello/"
components.queryItems = array.map { URLQueryItem(name: "value", value: [=10=])}
return components.url
}
2019
private func tellServerSomething(_ d: String, _ s: String) {
var c = URLComponents(string: "https://you.com/info")
c?.queryItems = [
URLQueryItem(name: "description", value: d),
URLQueryItem(name: "summary", value: s)
]
guard let u = c?.url else { return print("url fail") }
do {
let r = try String(contentsOf: u)
print("Server response \(r)")
}
catch { return print("comms fail") }
}
百分比编码和其他所有内容都已处理。
我在我的 iOS 应用程序中使用 AFNetworking,对于它发出的所有 GET 请求,我从基础 URL 构建 url,然后使用 NSDictionary 键添加参数-值对。
问题是不同的值需要相同的密钥。
这是我需要最终 URL 看起来像的示例 -
http://example.com/.....&id=21212&id=21212&id=33232
在 NSDictionary 中不可能在相同的键中有不同的值。所以我尝试了 NSSet 但没有成功。
let productIDSet: Set = [prodIDArray]
let paramDict = NSMutableDictionary()
paramDict.setObject(productIDSet, forKey: "id")
我想你只需要做这样的事情:
let params = ["id" : [1, 2, 3, 4], ...];
这将被编码成: ....id%5B%5D=1&id%5B%5D=2&id%5B%5D=3&id%5B%5D=4....
您只需要 URLComponents
(或 Obj-C 中的 NSURLComponents)。基本思想是为您的 ID 创建一堆查询项。您可以将以下代码粘贴到 playground 中:
import Foundation
import XCPlayground
let queryItems = [URLQueryItem(name: "id", value: "1"), URLQueryItem(name: "id", value: "2")]
var urlComps = URLComponents(string: "www.apple.com/help")!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)
您应该会看到
的输出www.apple.com/help?id=1&id=2
func queryString(_ value: String, params: [String: String]) -> String? {
var components = URLComponents(string: value)
components?.queryItems = params.map { element in URLQueryItem(name: element.key, value: element.value) }
return components?.url?.absoluteString
}
方法一
它可以将 QueryItem 添加到您现有的 URL。
extension URL {
func appending(_ queryItem: String, value: String?) -> URL {
guard var urlComponents = URLComponents(string: absoluteString) else { return absoluteURL }
// Create array of existing query items
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
// Create query item
let queryItem = URLQueryItem(name: queryItem, value: value)
// Append the new query item in the existing query items array
queryItems.append(queryItem)
// Append updated query items array in the url component object
urlComponents.queryItems = queryItems
// Returns the url from new url components
return urlComponents.url!
}
}
使用方法
var url = URL(string: "https://www.example.com")!
let finalURL = url.appending("test", value: "123")
.appending("test2", value: nil)
方法二
在此方法中,URL 将自动更新。
extension URL {
mutating func appendQueryItem(name: String, value: String?) {
guard var urlComponents = URLComponents(string: absoluteString) else { return }
// Create array of existing query items
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
// Create query item
let queryItem = URLQueryItem(name: name, value: value)
// Append the new query item in the existing query items array
queryItems.append(queryItem)
// Append updated query items array in the url component object
urlComponents.queryItems = queryItems
// Returns the url from new url components
self = urlComponents.url!
}
}
// How to use
var url = URL(string: "https://www.example.com")!
url.appendQueryItem(name: "name", value: "bhuvan")
用于附加查询项的 URL 扩展,类似于 Bhuvan Bhatt 的想法,但具有不同的签名:
- 它可以检测故障(通过返回
nil
而不是self
),因此允许自定义处理 URL 不符合 RFC 3986 的情况。 - 它允许 nil 值,实际上将任何查询项作为参数传递。
- 为了性能,它允许一次传递多个查询项。
extension URL {
/// Returns a new URL by adding the query items, or nil if the URL doesn't support it.
/// URL must conform to RFC 3986.
func appending(_ queryItems: [URLQueryItem]) -> URL? {
guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
// URL is not conforming to RFC 3986 (maybe it is only conforming to RFC 1808, RFC 1738, and RFC 2732)
return nil
}
// append the query items to the existing ones
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems
// return the url from new url components
return urlComponents.url
}
}
用法
let url = URL(string: "https://example.com/...")!
let queryItems = [URLQueryItem(name: "id", value: nil),
URLQueryItem(name: "id", value: "22"),
URLQueryItem(name: "id", value: "33")]
let newUrl = url.appending(queryItems)!
print(newUrl)
输出:
在Swift中用多个参数形成URL
func rateConversionURL(with array: [String]) -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "example.com"
components.path = "/hello/"
components.queryItems = array.map { URLQueryItem(name: "value", value: [=10=])}
return components.url
}
2019
private func tellServerSomething(_ d: String, _ s: String) {
var c = URLComponents(string: "https://you.com/info")
c?.queryItems = [
URLQueryItem(name: "description", value: d),
URLQueryItem(name: "summary", value: s)
]
guard let u = c?.url else { return print("url fail") }
do {
let r = try String(contentsOf: u)
print("Server response \(r)")
}
catch { return print("comms fail") }
}
百分比编码和其他所有内容都已处理。