我想在我的 url 字符串中对 +
字符进行编码,我尝试这样做:
let urlString = "www.google.com?type=c++"
let result = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
但这不适用于 +
。
有什么想法吗?谢谢。
更新:
而且 url 中的这个 type=
参数是动态的,我不会对 +
字符进行一些隐式替换。此 type=
参数表示一个 UITextField 值,因此可以输入任何内容。
我也很好奇为什么 addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
在这种特殊情况下不起作用?
最佳答案
let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted
if let escapedString = "www.google.com?type=c++".addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
print(escapedString)
}
输出:
www.google.com%3Ftype%3Dc%2B%2B
关于ios - 如何在 url 字符串中编码 '' +' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41697686/