Swift URL appendingPathComponent 将 `?` 转换为 `%3F`

Swift URL appendingPathComponent converts `?` to `%3F`

let url = URL(string: "https://example.com")
let path = "/somePath?"
let urlWithPath = url?.appendingPathComponent(path)

添加后,路径/somePath?变为somePath%3F

?变成了%3F。问号替换为百分比编码的转义字符。

如果我使用:

,URL 会正确输出
let urlFormString = URL(string:"https://example.com/somePath?")

为什么 appendingPathComponent? 转换为 %3F

如果路径部分包含问号,我如何使用 appendingPathComponent

%3F代表?,按照URL编码。所以如果你创建一个 URL - 它必须是那样的。如果出于某种原因,您需要 ?,请创建一个字符串,而不是 URL。

检查urlWithPath.lastPathComponent一切正常(打印:"somePath?")

当您将字符串转换为 URL 时,它将在 URL 中执行 PercentEncoding。这样你的?就被编码成了%3F.

如果你想要 url 作为带有 ? 的字符串,你可以像下面的代码一样删除 PercentEncoding。

let urlString = urlWithPath?.absoluteString.removingPercentEncoding

Output: https://example.com/somePath?

首先这不是问题。这是一种称为 URL 编码的机制,用于将不可打印或特殊字符转换为网络服务器和浏览器普遍接受的格式。

有关更多信息,您可以转到 https://www.techopedia.com/definition/10346/url-encoding

URL 编码字符,https://www.degraeve.com/reference/urlencoding.php

您应该在 URL 的 absoluteString

上使用 removingPercentEncoding
let url = URL(string: "https://example.com")
let path = "/somePath?"
let urlWithPath = url?.appendingPathComponent(path).absoluteString.removingPercentEncoding
print(urlWithPath!)

URL的通用格式如下:

scheme:[//[userinfo@]host[:port]]path[?query][#fragment]

你必须意识到 ? 不是 path 的一部分。它是 pathquery 之间的分隔符。

如果您尝试将 ? 添加到路径,它必须是 URL 编码的,因为 ? 不是路径组件的有效字符。

最好的解决方案是从 path 中删除 ?。它在那里没有任何意义。但是,如果您有一个部分 URL 想要附加到基数 URL,那么您应该将它们作为字符串加入:

let url = URL(string: "https://example.com")
let path = "/somePath?"
let urlWithPath = url.flatMap { URL(string: [=11=].absoluteString + path) }

简而言之,appendingPathComponent 不是应该用于附加 URL 查询的函数。

您可以使用 NSString class:

构建您的 url
let urlStr = "https://example.com" as NSString
let path = "/somePath?"
let urlStrWithPath = urlStr.appendingPathComponent(path)
let url = URL(string: urlStrWithPath)

这样,最后的url.

中就没有特殊字符了url-encoded