URLComponents : + , . + , .alphanumerics, ( , , !).
. OP value: "\($1)" , ; value:$1. URL- .
, , , , Forest Kunecke, , , , :
let queryParams = ["hey":"ho+ha"]
var components = URLComponents()
components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
components.queryItems = queryParams.map {
URLQueryItem(name: $0,
value: $1.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!)
}
let finalURL = components.url
EDIT It’s rather better, perhaps, after the proposed correction from Martin R: we form the entire request and quote the fragments themselves and tell URLComponents that we did this:
let queryParams = ["hey":"ho+ha", "yo":"de,ho"]
var components = URLComponents()
components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
var cs = CharacterSet.urlQueryAllowed
cs.remove("+")
components.percentEncodedQuery = queryParams.map {
$0.addingPercentEncoding(withAllowedCharacters: cs)! +
"=" +
$1.addingPercentEncoding(withAllowedCharacters: cs)!
}.joined(separator:"&")
components.queryItems
components.url
source
share