如何在Swift中使用包含相同键的多个值的查询参数构建URL? [英] How can I build a URL with query parameters containing multiple values for the same key in Swift?
问题描述
我正在iOS应用程序中使用AFNetworking,并且对于它发出的所有GET请求,我都会从基本URL构建URL,然后使用NSDictionary键值对添加参数.
I am using AFNetworking in my iOS app and for all the GET requests it makes, I build the url from a base URL and than add parameters using NSDictionary Key-Value pairs.
问题是我需要为不同的值使用相同的键.
The problem is that I need same key for different values.
以下是我需要最终URL看起来像的一个示例-
Here is an example of what I need the finally URL to look like -
http://example.com/. ....& id = 21212& id = 21212& id = 33232
在NSDictionary中,不可能在相同的键中具有不同的值.所以我尝试了NSSet但没有用.
It's not possible in NSDictionary to have different values in same keys. So I tried NSSet but did not work.
let productIDSet: Set = [prodIDArray]
let paramDict = NSMutableDictionary()
paramDict.setObject(productIDSet, forKey: "id")
推荐答案
您需要的只是URLComponents
(或Obj-C中的NSURLComponents).基本思想是为您的ID创建一堆查询项.您可以将以下代码粘贴到运动场中:
All you need is URLComponents
(or NSURLComponents in Obj-C). The basic idea is to create a bunch of query items for your id's. Here's code you can paste into a 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
www.apple.com/help?id=1&id=2
这篇关于如何在Swift中使用包含相同键的多个值的查询参数构建URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!