Created
December 1, 2015 17:56
-
-
Save blixt/7743cf400325395ca46c to your computer and use it in GitHub Desktop.
Parse query string from NSURL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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