Skip to content

Instantly share code, notes, and snippets.

@blixt
Created December 1, 2015 17:56
Show Gist options
  • Save blixt/7743cf400325395ca46c to your computer and use it in GitHub Desktop.
Save blixt/7743cf400325395ca46c to your computer and use it in GitHub Desktop.
Parse query string from NSURL
// Example:
let url = NSURL(string: "https://example.com/hello?bla=one&bla=two&foo&bar=1")!
let values = url.parseQueryString()
// Result: ["bla": ["one", "two"], "bar": ["1"], "foo": []]
extension NSURL {
func parseQueryString() -> [String: [String]]? {
guard let items = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)?.queryItems else {
return nil
}
var data = [String: [String]]()
for item in items {
var list = data[item.name] ?? [String]()
if let value = item.value {
list.append(value)
}
data[item.name] = list
}
return data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment