JMS JMS - 8 months ago 67
iOS Question

Swift: Get all key value pairs from a String

I have a

which has many key value pairs appended by a
sign. i.e:
params = key1=Hello&key2=Hello World&key3=Hi Hello

Is there a way to extract the values just by passing the keys present in the string? For example I want to extract the value of key1, key2, key3.

Answer Source

You can use URLComponents and URLQueryItem anyway by creating a dummy URL

let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
if let components = URLComponents(string: "" + params.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!),
    let queryItems = components.queryItems {
    let arrayOfValues = queryItems.flatMap{ $0.value }

see also Best way to parse URL string to get values for keys?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download