4

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?

Robert
  • 3,790
  • 1
  • 27
  • 46

3 Answers3

6
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

Viktor Gardart
  • 3,782
  • 3
  • 17
  • 24
  • Yes, your approach is well enough (not ideal), but I'm curious why `addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)` won't work... – Robert Jan 17 '17 at 13:19
  • That's something i can't answer, they've probably not added the `+` to that for some good reason. – Viktor Gardart Jan 17 '17 at 13:21
3

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

Jonas Deichelmann
  • 3,513
  • 1
  • 30
  • 45
1

Replace + with %2B

let urlString = "www.google.com?type=c++"
let newUrlString = aString.replacingOccurrences(of: "+", with: "%2B")
Fawad Masud
  • 12,219
  • 3
  • 25
  • 34