URL Encoding of String accepting all special characters in swift

烂漫一生 提交于 2019-12-13 09:01:33

问题


Trying to encode string added with special characters with below code:

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

which does not include all special characters.

Also tried below options:

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

but it's not working.

Please tell me if there is any other approach for URL encoding to include all special characters.

Edit

Adding : as input in string it converts to %3A. Same way for @ - %40.

But adding & remains same. Required output is %26.


回答1:


Thank you @MartinR and @benleggiero for : How do I URL encode a string

It helped a lot.

It was not including all special characters.

Checked one by one and added those which were missing as below:

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
    }
}


来源:https://stackoverflow.com/questions/48093256/url-encoding-of-string-accepting-all-special-characters-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!