Encoding HTTP GET parameters

by @ralfebert · updated July 15, 2021
Xcode 13 & iOS 15
Swift Examples

Use URLComponents.queryItems to percent-encode an URL string with HTTP GET parameters:

var urlComponents = URLComponents(string: "https://www.google.de/maps/")!
urlComponents.queryItems = [
    URLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
    URLQueryItem(name: "z", value: String(6))
]
urlComponents.url      // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6

More information