Search code examples
swifturlspecial-charactersencodensurl

Swift Quotation Mark in URL


I'm trying to do a request with Alamofire to this url:

https://overpass-api.de/api/interpreter?data=[out:json];(way[highway~"^(motorway)$"][!maxspeed](around:5,45.792790,3.062686););out%20tags;

but it contains a double quotation mark and the cast into URL fails.

I've escaped the " with the backslash

let urlString = "https://overpass-api.de/api/interpreter?data=[out:json];(way[highway~\"^(motorway)$\"][!maxspeed](around:5,45.792790,3.062686););out%20tags;"

but when I convert the string in a URL, it returns nil

let url = URL(string: urlString)

I've tried replacing the " symbols with %22, but it is still not working. I tried using the addingPercent but it results in a wrong url and returns error 400 or 404

let urlWithEconding = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

I also tried to use AlamoFire method for url casting and encoding, but I cannot make it work...


Solution

  • Here is how you can use URLComponents

    let queryValue = "[out:json];(way[highway~\"^(motorway)$\"][!maxspeed](around:5,45.792790,3.062686););out tags;"
    
    var components = URLComponents()
    
    components.scheme = "https"
    components.host = "overpass-api.de"
    components.path = "/api/interpreter"
    components.queryItems = [URLQueryItem(name: "data", value: queryValue)]
    

    If you don't want to escape the quotes you can define the variable like this

    let queryValue = """
    [out:json];(way[highway~"^(motorway)$"][!maxspeed](around:5,45.792790,3.062686););out tags;
    """