ios - 如何快速修复 URLQueryItem

标签 ios swift urlcomponents

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

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

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

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

%3 转换为 %253。为什么会出现这种情况?

最佳答案

不要对您提供给 URLQueryItem 的值进行百分比编码。 URLQueryItem 会为您完成此操作。事实上,您对其进行了双重百分比编码(即,它对百分比编码字符串的 % 进行百分比编码)。

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

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

顺便说一句,无论如何,在查询中遇到 : 字符时不需要进行百分比编码。例如:

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,您将看到 : 不需要转义。

但是,如果该查询中确实有任何内容需要百分比编码,URLQueryItemURLComponents 将为您处理。 (一个异常(exception)是 + 字符如 discussed here ;但我从你的例子中假设你不希望它被转义。)

关于ios - 如何快速修复 URLQueryItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72250983/

相关文章:

ios - Firebase Auth - 获取提供商 ID

ios - XCode:仪器有堆栈跟踪吗?

iphone - 如何在GameCenter应用程序中支持多个游戏

ios - 从 iOS 上的 mov 文件中提取元数据

swift - 全局控制按钮外观

ios - CGImageCreateWithImageInRect() 返回零

iphone - iPhone 应用程序中的 OAuth 集成