I need to pass simple dictionary:
var dictionary: [AnyHashable: Any] = [
"a": 1,
"b": "title",
"c": ["a", "b"],
"d": ["a": 1, "b": ["a", "b"]]
]
to URL:
let url = URL(string: "http://example.com")!
How can I do this?
And from the other way, how to access parameters from URL?
The output in imessage:
Based on your parameter requirements I don't know if this is what you are looking for but...
If you would like to append and examine URL parameters you can use NSURLComponents
In your case you could get away with something like this:
var dictionary: [AnyHashable: Any] = [
"a": 1,
"b": "title",
"c": ["a", "b"],
"d": ["a": 1, "b": ["a", "b"]]
]
let url = URL(string: "http://example.com")!
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
let queryItems = dictionary.map{
return URLQueryItem(name: "\($0)", value: "\($1)")
}
urlComponents?.queryItems = queryItems
print(urlComponents?.url) //gives me Optional(http://example.com?b=title&a=1&d=%5B%22b%22:%20%5B%22a%22,%20%22b%22%5D,%20%22a%22:%201%5D&c=%5B%22a%22,%20%22b%22%5D)
The interesting parts are the URLComponents
itself, which "explodes" the URL you give it into parts that you can then examine.
Then, to add URL query parameters you use the URLQueryItem
class and give an array of those URLQueryItem
items to your URLComponents
instance. In this quick example I just map
from your dictionary to an array of URLQueryItem
s but you can probably think of something a bit more solid :)
URLComponents
can of course also be used the other way around...I mean, if you have an URL with parameters you can create an instance of URLComponents
and then query the queryItems
.
Hope that helps you.
If you simply want to create a parameter string from the dictionary of values, and you want it to be simple, you can do something like this:
var str = ""
for key in dictionary.keys {
if str.isEmpty {
str = "\(key)=\(dictionary[key]!)"
} else {
str += "&\(key)=\(dictionary[key]!)"
}
However, the above does not encode special characters nor does it do any other special handling. So, a better option would be to add an extension to Dictionary along the following lines:
extension Dictionary {
var queryParameters: String {
var parts: [String] = []
for (key, value) in self {
let part = String(format: "%@=%@",
String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,
String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
parts.append(part as String)
}
return parts.joined(separator: "&")
}
}
}
Then, you can simply say dictionary.queryParameters
to get a string which has the dictionary content converted into a parameter string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With