How do I convert url.query to a dictionary in Swift?

Varun Naharia picture Varun Naharia · Oct 6, 2017 · Viewed 9k times · Source

I have a URL coming in to the AppDelegate method:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
}

The URL looks like www.wesite.com/shareplace.html?placeid=123.

How can it be converted to a dictionary for easy access?

I found some code on some website, but it's showing an error in Xcode 9:

 extension URL {
    var queryDictionary: [String: AnyObject]? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?
            .queryItems?
            .reduce([:], combine: { (var result: [String: AnyObject], queryItem) -> [String: AnyObject] in
                if queryItem.value?.containsString(",") ?? false {
                    let array = queryItem.value?.componentsSeparatedByString(",")

                    result[queryItem.name] = array
                }
                else {
                    result[queryItem.name] = queryItem.value
                }

                return result
            })
    }
}

.reduce([:], combine: { (var result: [String: AnyObject], queryItem) -> [String: AnyObject] in (var result) Parameters may not have the 'var' specifier

Answer

Hexfire picture Hexfire · Oct 6, 2017

Simple Extension

extension URL {
    var queryDictionary: [String: String]? {
        guard let query = self.query else { return nil}

        var queryStrings = [String: String]()
        for pair in query.components(separatedBy: "&") {

            let key = pair.components(separatedBy: "=")[0]

            let value = pair
                .components(separatedBy:"=")[1]
                .replacingOccurrences(of: "+", with: " ")
                .removingPercentEncoding ?? ""

            queryStrings[key] = value
        }
        return queryStrings
    }
}

USAGE

let urlString = "http://www.youtube.com/video/4bL4FI1Gz6s?hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104"
let url = URL(string: urlString)
print(url!.queryDictionary ?? "NONE")