gpt4 book ai didi

ios - `addingPercentEncoding` 在 Xcode 9 中损坏了吗?

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:45 25 4
gpt4 key购买 nike

在带有 Xcode 9 beta 2 的 Swift 3.x 中,使用 addingPercentEncoding给出意想不到的结果。 CharacterSet.urlPathAllowed 始终包含“:”,因此根据 addingPercentEncoding 的定义,它永远不应转义。然而,使用这段代码:

// always true
print(CharacterSet.urlPathAllowed.contains(":"))
let myString = "info:hello world"
let escapedString = myString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
print(escapedString)

我得到了那些结果:

我遇到不良行为的情况

  • Xcode 9 beta 2,iOS 9.3
  • Xcode 9 测试版 2,iOS 11.0

    true
    info%3Ahello%20world

我得到预期行为的情况

  • Xcode 9 测试版 2,iOS 10.3.1
  • Xcode 8.3.3,任何 iOS

    true
    info:hello%20world

是否有任何变通方法可以使 addingPercentEncoding 的工作实现正确遵守给定的 allowedCharacters

最佳答案

显然,当用作引用的 CharacterSet 是底层 NSCharacterSet 类时,addingPercentEncoding 完成了一些未记录的魔法。

因此,要解决这个问题,您需要让您的 CharacterSet 成为一个纯 Swift 对象。为此,我将创建一个副本(感谢 Martin R!),这样邪恶的魔法就消失了:

let myString = "info:hello world"
let csCopy = CharacterSet(bitmapRepresentation: CharacterSet.urlPathAllowed.bitmapRepresentation)
let escapedString = myString.addingPercentEncoding(withAllowedCharacters: csCopy)!
//always "info:hello%20world"
print(escapedString)

作为扩展:

extension String {
func safeAddingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
// using a copy to workaround magic: https://stackoverflow.com/q/44754996/1033581
let allowedCharacters = CharacterSet(bitmapRepresentation: allowedCharacters.bitmapRepresentation)
return addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
}

关于ios - `addingPercentEncoding` 在 Xcode 9 中损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44754996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com