Created
November 17, 2014 02:21
-
-
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]]
This file contains 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
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 | |
} | |
} | |
} |
let query = url.queryDictionary
let code = query?["code"]
@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
what is the usage of this if i try i am getting compiler errors:
'[String : [String]]?' does not have a member named 'subscript'