我正在尝试使用 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 方法进行 url 转换和编码,但我无法使其工作......
最佳答案
以下是如何使用 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)]
如果你不想转义引号,你可以像这样定义变量
let queryValue = """
[out:json];(way[highway~"^(motorway)$"][!maxspeed](around:5,45.792790,3.062686););out tags;
"""
关于URL 中的 Swift 引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274434/