-1

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.

Amit
  • 4,837
  • 5
  • 31
  • 46

1 Answers1

2

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
    }
}
Amit
  • 4,837
  • 5
  • 31
  • 46