ios - 如何在 url 字符串中编码 '' +' 字符?

标签 ios swift url swift3

我想在我的 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/

相关文章:

ios - 在 iOS 14 升级中未加载 react-native 图像

ios - AFNetworking 和批处理/串行操作

swift - 即使在初始化之后,让常量看起来也是可变的

ios - Segue 不适用于静态 UITableView

mysql - 通过包含 jQuery 的 Img Src 变量更新 MySQL 值

php - 是否可以仅对特定引用和 URL 使用 <base> 标记?

iOS,钥匙串(keychain) : Wrong passcode output

ios - 如何移动 MKMapView 的中心,以便默认位置图标转到底部中心

ios - 如何使用 Swift 在 SpriteKit 中重置 NSUserDefaults 的高分

javascript - 如何从 URL 获取 YouTube 视频 ID?