Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode ''+' character in url string?

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?

like image 414
Robert Avatar asked Mar 11 '23 03:03

Robert


1 Answers

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

like image 67
Viktor Gardart Avatar answered Mar 20 '23 06:03

Viktor Gardart