Skip to content

Instantly share code, notes, and snippets.

@hudinwal
Created February 23, 2017 16:39
Show Gist options
  • Save hudinwal/3230167076897dcb4a46e6a28ff7d411 to your computer and use it in GitHub Desktop.
Save hudinwal/3230167076897dcb4a46e6a28ff7d411 to your computer and use it in GitHub Desktop.
import UIKit
/*
Extension with queryItems to Dictionary and Dictionary to queryItems
*/
extension URLComponents {
/*
Get the dictionary from queryItems
*/
var queryItemsAsDictionary: [String:String?]? {
guard let queryItems = queryItems else {
return nil
}
var dict:[String:String?] = [:]
for item in queryItems {
dict[item.name] = item.value
}
return dict
}
/*
Replace the queryItems from items in dictionary
*/
mutating func replaceQueryItems(fromDictionary dictionary:[String:String?]?) {
guard let dictionary = dictionary, dictionary.count > 0 else {
queryItems = nil
return
}
var newQueries:[URLQueryItem]? = nil
for (name,value) in dictionary {
if newQueries == nil { newQueries = [] }
let queryItem = URLQueryItem(name: name, value: value)
newQueries?.append(queryItem)
}
queryItems = newQueries
}
}
var components = URLComponents(string: "htttps://www.server/somepath/anotherpath?keyA=valueA,keyB=valueB")
print(components?.url ?? "NIL")
var queryDictionary = components?.queryItemsAsDictionary
queryDictionary?["keyC"] = "valueC"
components?.replaceQueryItems(fromDictionary: queryDictionary)
print(components?.url ?? "NIL")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment