为何removingPercentEncoding()不替换+?如何解码两种URL编码字符串?
URL空格编码解码问题解答
先看你给出的代码示例:
let first = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test" let second = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New%20calendar%20test" let firstOutput = first.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test let secondOutput = second.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New calendar test
问题1:既然+是空格的合法编码,为何removingPercentEncoding无法正确解码?
removingPercentEncoding的核心作用是仅解码百分号格式的编码字符(比如%20),而+作为空格的替代是application/x-www-form-urlencoded格式(URL查询参数的标准格式)里的特殊约定,不属于通用的百分号解码规则。这个方法不会识别这种特定场景下的+转空格逻辑,所以不会处理它。
问题2:无论收到哪种编码的字符串,如何正确解码?
有两种靠谱的处理方式:
方式一:先替换+为%20再解码
先把字符串里的+统一替换成%20,再调用removingPercentEncoding,这样两种空格编码都能被正确处理:
func decodeURLString(_ string: String) -> String? { let plusReplaced = string.replacingOccurrences(of: "+", with: "%20") return plusReplaced.removingPercentEncoding } // 测试结果 let firstDecoded = decodeURLString(first) // 输出:https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New calendar test let secondDecoded = decodeURLString(second) // 输出:https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New calendar test
方式二:用URLComponents规范处理(推荐)
如果是完整的URL字符串,用URLComponents来处理更规范,它会自动识别查询参数里的+并转成空格,同时处理百分号编码:
func decodeURLWithComponents(_ string: String) -> String? { guard var components = URLComponents(string: string) else { return nil } // 确保查询参数里的+被正确替换 components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%20") return components.url?.absoluteString } // 测试结果 let firstDecoded2 = decodeURLWithComponents(first) let secondDecoded2 = decodeURLWithComponents(second)
内容的提问来源于stack exchange,提问作者kunass2
相关产品推荐
相关产品推荐

