Skip to content

Instantly share code, notes, and snippets.

@kylehowells
Created November 17, 2014 02:21
Show Gist options
  • Save kylehowells/1215df277d750af71887 to your computer and use it in GitHub Desktop.
Save kylehowells/1215df277d750af71887 to your computer and use it in GitHub Desktop.
Turns an NSURL's -query string into a dictionary. Sadly URL's allow keys to be declared multiple times, so it is a dictionary of String of the keys and arrays of Strings as the objects. [String: [String]]
extension NSURL
{
@objc var queryDictionary:[String: [String]]? {
get {
if let query = self.query {
var dictionary = [String: [String]]()
for keyValueString in query.componentsSeparatedByString("&") {
var parts = keyValueString.componentsSeparatedByString("=")
if parts.count < 2 { continue; }
var key = parts[0].stringByRemovingPercentEncoding!
var value = parts[1].stringByRemovingPercentEncoding!
var values = dictionary[key] ?? [String]()
values.append(value)
dictionary[key] = values
}
return dictionary
}
return nil
}
}
}
@johnbeynon
Copy link

let query = url.queryDictionary
let code = query?["code"]

@kylehowells
Copy link
Author

@romk1n As it returns an array of keys but there will likely only be one (didn't know there could be multiples before writing this) you'll likely want to use.

let query = url.queryDictionary
let code = query?["code"]?.first

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment