【问题标题】:Swift Quotation Mark in URLURL 中的 Swift 引号
【发布时间】:2020-04-04 01:33:41
【问题描述】:

我正在尝试使用 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,但仍然无法正常工作。我尝试使用添加百分比,但它导致错误的 url 并返回错误 400 或 404

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

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

【问题讨论】:

  • 永远不要使用带有字符串的 URL。使用 URLComponents。
  • 你能给我看一个使用 URLComponents 的例子吗? ?data= 之后的部分是否必须被视为 queryItems?
  • 如果您也是 API 的开发人员,您可能希望将参数作为标头而不是 URL 组件传递。我相信 JSON通常通过请求标头传递给 API。

标签: swift url special-characters encode nsurl


【解决方案1】:

以下是如何使用 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;
"""

【讨论】:

  • 我使用了 URLComponents,效果很好,谢谢
猜你喜欢
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多