I have a dictionary as [String:Any]
.Now i want to convert this dictionary keys & value as key=value&key=value
.I have created below extension to work but it didn't work for me.
extension Dictionary {
var queryString: String? {
var output: String = ""
for (key,value) in self {
output += "\(key)=\(value)\(&)"
}
return output
}
}
Use NSURLQueryItem.
An NSURLQueryItem object represents a single name/value pair for an item in the query portion of a URL. You use query items with the queryItems property of an NSURLComponents object.
To create one use the designated initializer queryItemWithName:value:
and then add them to NSURLComponents
to generate an NSURL
. For example:
OBJECTIVE-C:
NSDictionary *queryDictionary = @{ @"q": @"ios", @"count": @"10" };
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in queryDictionary) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:queryDictionary[key]]];
}
components.queryItems = queryItems;
NSURL *url = components.URL; // http://stackoverflow.com?q=ios&count=10
Swift:
let queryDictionary = [ "q": "ios", "count": "10" ]
var components = URLComponents()
components.queryItems = queryDictionary.map {
URLQueryItem(name: $0, value: $1)
}
let URL = components.url
Another Swift-esque approach:
let params = [
"id": 2,
"name": "Test"
]
let urlParams = params.flatMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
var populatedDictionary = ["key1": "value1", "key2": "value2"]
extension Dictionary {
var queryString: String {
var output: String = ""
for (key,value) in self {
output += "\(key)=\(value)&"
}
output = String(output.characters.dropLast())
return output
}
}
print(populatedDictionary.queryString)
// Output : key1=value1&key2=value2
Hope it helps. Happy Coding!!
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