Search code examples
iosswiftswift2nsurl

How can I build a URL with query parameters containing multiple values for the same key in Swift?


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.

Here is an example of what I need the finally URL to look like -

http://example.com/.....&id=21212&id=21212&id=33232

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")

Solution

  • 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)
    

    You should see an output of

    www.apple.com/help?id=1&id=2