URL中的快速引号

问题描述 投票:0回答:1

我正在尝试与Alamofire对此网址进行请求:

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

但是它包含双引号,并且强制转换为URL失败。

我用反斜杠转义了"

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

但是当我在URL中转换字符串时,它返回nil

let url = URL(string: urlString)

我曾尝试用"替换%22符号,但仍然无法正常工作。我尝试使用addingPercent,但它导致了错误的URL,并返回错误400或404

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

我也尝试过使用AlamoFire方法进行网址转换和编码,但是我无法使其工作...

swift url special-characters encode nsurl
1个回答
0
投票

这里是使用URLComponents的方法

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

var components = URLComponents()

components.scheme = "https"
components.host = "overpass-api.de"
components.path = "/api/interpreter"
components.queryItems = [URLQueryItem(name: "data", value: queryValue)]

如果您不想转义引号,则可以这样定义变量

let queryValue = """
[out:json];(way[highway~"^(motorway)$"][!maxspeed](around:5,45.792790,3.062686););out%20tags;
"""
© www.soinside.com 2019 - 2024. All rights reserved.