How can I build a URL with query parameters contai

2020-02-08 09:42发布

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

8条回答
家丑人穷心不美
2楼-- · 2020-02-08 10:33

In Swift Forming URL with multiple params

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: $0)}

        return components.url
    }
查看更多
叛逆
3楼-- · 2020-02-08 10:36

It can add the QueryItem to your existing 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!
    }
}

How to use

var url = URL(string: "https://www.example.com")!
let finalURL = url.appending("test", value: "123")
                  .appending("test2", value: nil)
查看更多
登录 后发表回答