URL 中的 Swift 引号

标签 swift url special-characters encode nsurl

我正在尝试使用 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/

相关文章:

ios - 如何从 iOS 的排行榜中检索分数?

ios - AppDelegate 中的 UITextField 自定义不适用于 Swift

swift - 在 swift 中将带有参数的函数分配给变量

asp.net - 无法创建特殊字符的图像

ios - DDMathParser:解析包含 $ 的动态公式以引用字典中的对象值

javascript - jQuery:向 URL 哈希写入和读取参数的轻量级方法?

php - 不带 GET 参数的请求字符串

javascript - 谷歌驱动器公共(public)

unicode - 奇怪的(unicode?)字符

html - 如何使用javascript在jsx中重复插入特殊字符?