URL的URL编码接受swift中的所有特殊字符

时间:2018-01-04 10:26:35

标签: ios swift urlencode

尝试编码使用以下代码添加特殊字符的字符串:

let encodedString = myString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

不包括所有特殊字符。

还尝试了以下选项:

  • .urlHostAllowed
  • .urlFragmentAllowed
  • .urlPasswordAllowed
  • .urlPathAllowed
  • .urlUserAllowed
  • .urlQueryAllowed

但它不起作用。

请告诉我是否有其他网址编码方法可以包含所有特殊字符。

修改

在字符串中添加:作为输入,转换为%3A。同样适用于@ - %40

但添加&仍然相同。所需输出为%26

1 个答案:

答案 0 :(得分:0)

感谢@MartinR和@benleggiero:How do I URL encode a string

它帮助了很多。

它没有包含所有特殊字符。

逐一检查并添加如下缺失的那些:

extension CharacterSet {

    public static let urlQueryParameterAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&?~!$*(.,)_-+':"))

    public static let urlQueryDenied           = CharacterSet.urlQueryAllowed.inverted()
    public static let urlQueryKeyValueDenied   = CharacterSet.urlQueryParameterAllowed.inverted()
    public static let urlPathDenied            = CharacterSet.urlPathAllowed.inverted()
    public static let urlFragmentDenied        = CharacterSet.urlFragmentAllowed.inverted()
    public static let urlHostDenied            = CharacterSet.urlHostAllowed.inverted()

    public static let urlDenied                = CharacterSet.urlQueryDenied
        .union(.urlQueryKeyValueDenied)
        .union(.urlPathDenied)
        .union(.urlFragmentDenied)
        .union(.urlHostDenied)


    public func inverted() -> CharacterSet {
        var copy = self
        copy.invert()
        return copy
    }
}