Convert dictionary to query string in swift?
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!!
How do I convert url.query to a dictionary in Swift?
Simple Extension
extension URL {
var queryDictionary: [String: String]? {
guard let query = self.query else { return nil}
var queryStrings = [String: String]()
for pair in query.components(separatedBy: "&") {
let key = pair.components(separatedBy: "=")[0]
let value = pair
.components(separatedBy:"=")[1]
.replacingOccurrences(of: "+", with: " ")
.removingPercentEncoding ?? ""
queryStrings[key] = value
}
return queryStrings
}
}
USAGE
let urlString = "http://www.youtube.com/video/4bL4FI1Gz6s?hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104"
let url = URL(string: urlString)
print(url!.queryDictionary ?? "NONE")
How to build a URL by using Dictionary in Swift
Here is a code snippet to convert dictionary to URLQueryItems
:
let dictionary = [
"name": "Alice",
"age": "13"
]
func queryItems(dictionary: [String:String]) -> [URLQueryItem] {
return dictionary.map {
// Swift 3
// URLQueryItem(name: $0, value: $1)
// Swift 4
URLQueryItem(name: $0.0, value: $0.1)
}
}
var components = URLComponents()
components.queryItems = queryItems(dictionary: dictionary)
print(components.url!)
Encode url string to Dictionary In my case: Some value have = inside
Piggyback on URLComponents
:
var components = URLComponents()
components.query = "id=sfghsgh=sbfsfhj&name=awsjdk_fs"
components.queryItems
// => Optional([id=sfghsgh=sbfsfhj, name=awsjdk_fs])
let list = components.queryItems?.map { ($0.name, $0.value) } ?? []
// [("id", Optional("sfghsgh=sbfsfhj")), ("name", Optional("awsjdk_fs"))]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": Optional("awsjdk_fs"), "id": Optional("sfghsgh=sbfsfhj")]
If you need a [String: String]
rather than [String: String?]
:
let list = components.queryItems?.compactMap { ($0.name, $0.value) as? (String, String) } ?? []
// [("id", "sfghsgh=sbfsfhj"), ("name", "awsjdk_fs")]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": "awsjdk_fs", "id": "sfghsgh=sbfsfhj"]
Convert nested dictionary to create String Swift
With:
struct Item {
let name: String?
let itemId: String?
}
let dict: [String: [Item]] = ["price": [Item(name: "10-25", itemId: "10-25")],
"publisher": [Item(name: "ABCD", itemId: "576"),
Item(name: "DEFG", itemId: "925"),
Item(name: "HIJK", itemId: "1737")]]
You could use:
var keys = ["price", "publisher"]
let reduced = keys.reduce(into: [String]()) { result, current in
guard let items = dict[current] else { return }
let itemsStr = items.compactMap {$0.itemId }.joined(separator: ",")
result.append("\(current):\(itemsStr)")
}
let finalStr = reduced.joined(separator: ";")
print(finalStr)
The idea:
Iterate over the needed keys (and order guaranteed), construct for each keys, the itemsIds list joined by "," and then append that with the key.
Finally, joined all that.
Add-on questions:
Why is name
and itemId
optional? Is that normal?
Site note: giving the first part (easily reproducible input) can increase the change of answers, so we don't have to recreate ourselves fake data to check our answers.
Convert a Dictionary to string of url parameters?
One approach would be:
var url = string.Format("http://www.yoursite.com?{0}",
HttpUtility.UrlEncode(string.Join("&",
parameters.Select(kvp =>
string.Format("{0}={1}", kvp.Key, kvp.Value)))));
You could also use string interpolation as introduced in C#6:
var url = $"http://www.yoursite.com?{HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")))}";
And you could get rid of the UrlEncode
if you don't need it, I just added it for completeness.
Best way to parse URL string to get values for keys?
edit (June 2018): this answer is better. Apple added NSURLComponents
in iOS 7.
I would create a dictionary, get an array of the key/value pairs with
NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"];
Then populate the dictionary :
for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
[queryStringDictionary setObject:value forKey:key];
}
You can then query with
[queryStringDictionary objectForKey:@"ad_eurl"];
This is untested, and you should probably do some more error tests.
Related Topics
Use Uipangesturerecognizer to Drag Uiview Inside Limited Area
Swift Didset Get Index of Array
Open File Dialog Crashes in Swift
Swiftui - Foreach Deletion Transition Always Applied to Last Item Only
"Cannot Inherit from Non-Open Class" Swift
How to Set an Attributed Title Color for State in Swift
Calling a Global Function Which Has the Same Name as a Member Function
How to Check If 'Any(Not Any)' Is Nil or Not in Swift
Convert Dictionary to Query String in Swift
How to Manually Decode an an Array in Swift 4 Codable
Does Swift Have an Implicit Object Initializer, Like in C#
How to Open Another Window in MACos in Swift with Cocoa
What Is the Backslash(\) Used for in Swiftui
Creating a Custom Scngeometry Polygon Plane with Scngeometryprimitivetype Polygon Crash/Error
Adding a Search Bar to Navigationview in Swiftui
Correct Handling/Cleanup/Etc of Cadisplaylink in Swift Custom Animation
Understanding the Userdefaults Register Method
This Class Is Not Key Value Coding-Compliant for the Key Name.'