如何修复 swift 中的 URLQueryItem

How to fix URLQueryItem in swift

我需要将查询参数传递给我 URLComponents:

URLQueryItem(name: "scope", value: "channel%3Amanage%3Apolls+channel%3Aread%3Apolls")

但是当我在调试中看到 url 时,我看到了这个:

scope=channel%253Amanage%253Apolls+channel%253Aread%253Apolls

%3 转变为 %253。为什么会这样?

不要 percent-encode 您提供给 URLQueryItem 的值。 URLQueryItem 为您做到这一点。实际上,您是 percent-encoding 它的两倍(即,它是 percent-encoding 您的 percent-encoded 字符串的 %)。

因此,只需提供简单的字符串,让 URLComponents 处理它:

let queryItem = URLQueryItem(name: "scope", value: "channel:manage:polls+channel:read:polls")

顺便说一句,无论如何,在查询中遇到 : 字符时不需要 percent-encoded。例如:

let queryItem = URLQueryItem(name: "scope", value: "channel:manage:polls+channel:read:polls")

var components = URLComponents(string: "https://example.com")
components?.queryItems = [
    queryItem
]

guard let url = components?.url else { return }

print(url) // https://example.com?scope=channel:manage:polls+channel:read:polls

参见RFC3986,其中,如果您将query回溯到pchar,您会看到:不需要转义。

但如果该查询中确实有任何需要 percent-encoding 的内容,URLQueryItemURLComponents 会为您处理。 (一个例外是 + 字符作为 discussed here;但我从您的示例中假设您无论如何都不希望转义。)