Reputation: 3870
I want to encode the +
character in my url string, I tried to do that this way:
let urlString = "www.google.com?type=c++"
let result = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
but this won't work for +
.
any idea? Thanks.
Update:
What's more this type=
parameter in the url is dynamic, I wouldn't do some implicite replacement on the +
character. This type=
parameter represents a UITextField value, so there can be typed-in anything.
I'm also curious why addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
won't work in this particular case?
Upvotes: 6
Views: 3960
Reputation: 3743
Swift 5
Using an Extension and add the plus to the not allowed Characters, so you can create your own characterSet and reuse it everywhere you need it. :
extension CharacterSet {
/// Characters valid in part of a URL.
///
/// This set is useful for checking for Unicode characters that need to be percent encoded before performing a validity check on individual URL components.
static var urlAllowedCharacters: CharacterSet {
// You can extend any character set you want
var characters = CharacterSet.urlQueryAllowed
characters.subtract(CharacterSet(charactersIn: "+"))
return characters
}
}
Usage:
let urlString = "www.google.com?type=c++"
let result = urlString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters)
I found a list with the character sets for url encoding. The following are useful (inverted) character sets:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
Source: https://stackoverflow.com/a/24552028/8642838
Upvotes: 4
Reputation: 4490
let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted
if let escapedString = "www.google.com?type=c++".addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
print(escapedString)
}
Output:
www.google.com%3Ftype%3Dc%2B%2B
Upvotes: 7
Reputation: 12344
Replace + with %2B
let urlString = "www.google.com?type=c++"
let newUrlString = aString.replacingOccurrences(of: "+", with: "%2B")
Upvotes: 1