Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary to query string in swift?

Tags:

swift

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
    }
}
like image 430
TechChain Avatar asked Jun 30 '17 04:06

TechChain


3 Answers

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
like image 164
Lal Krishna Avatar answered Nov 08 '22 07:11

Lal Krishna


Another Swift-esque approach:

let params = [
    "id": 2,
    "name": "Test"
]

let urlParams = params.flatMap({ (key, value) -> String in
    return "\(key)=\(value)"
}).joined(separator: "&")
like image 44
kyleturner Avatar answered Nov 08 '22 06:11

kyleturner


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!!

like image 12
luckyShubhra Avatar answered Nov 08 '22 08:11

luckyShubhra