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 extensio
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!!
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
Add this function to your controller
func getQueryString(params : [String : Any])-> String{
let urlParams = params.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
var urlString = "?" + urlParams
if let url = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed){
urlString = url
}
return urlString
}
Example
self.getQueryString(params: ["name" : "deep ios developer" , "age" :22])
Compact version of @luckyShubhra's answer
Swift 5.0
extension Dictionary {
var queryString: String {
var output: String = ""
forEach({ output += "\($0.key)=\($0.value)&" })
output = String(output.dropLast())
return output
}
}
Usage
let populatedDictionary = ["key1": "value1", "key2": "value2"]
let urlQuery = populatedDictionary.queryString
print(urlQuery)
import Foundation
extension URL {
var queryItemsDictionary: [String: String] {
var queryItemsDictionary = [String: String]()
// we replace the "+" to space and then encode space to "%20" otherwise after creating URLComponents object
// it's not possible to distinguish the real percent from the space in the original URL
let plusEncodedString = self.absoluteString.replacingOccurrences(of: "+", with: "%20")
if let queryItems = URLComponents(string: plusEncodedString)?.queryItems {
queryItems.forEach { queryItemsDictionary[$0.name] = $0.value }
}
return queryItemsDictionary
}
}
That extension will allow you to parse URL where you have both encoded + sign and space with plus, for example:
https://stackoverflow.com/?q=First+question&email=mail%2B10@mail.com
That extension will parse "q" as "First question" and "email" as "mail+10@mail.com"