问题
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