我需要將查詢引數傳遞給我的URLComponents:
URLQueryItem(name: "scope", value: "channel:manage:polls channel:read:polls")
但是當我在除錯中看到 url 時,我看到了這個:
scope=channel%253Amanage%253Apolls channel%253Aread%253Apolls
中的%3變換%3。為什么會這樣?
uj5u.com熱心網友回復:
不要對您提供的值進行百分比編碼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,您將看到:不需要轉義。
但是,如果該查詢中確實有任何需要百分比編碼的內容,URLQueryItem并且URLComponents會為您處理。(一個例外是這里討論 的角色;但我從你的例子中假設你不希望它逃脫。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476599.html
