222

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it doesn't escape the slashes /.

I've searched and found this Objective C code:

NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                        NULL,
                        (CFStringRef)unencodedString,
                        NULL,
                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                        kCFStringEncodingUTF8 );

Is there an easier way to encode an URL and if not, how do I write this in Swift?

11 Answers 11

486

Swift 3

In Swift 3 there is addingPercentEncoding

var originalString = "test/test"
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)

Output:

test%2Ftest

Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

Output:

test%2Ftest

The following are useful (inverted) character sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

If you want a different set of characters to be escaped create a set:
Example with added "=" character:

var originalString = "test/test=42"
var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")

Output:

test%2Ftest%3D42

Example to verify ascii characters not in the set:

func printCharactersInSet(set: NSCharacterSet) {
    var characters = ""
    let iSet = set.invertedSet
    for i: UInt32 in 32..<127 {
        let c = Character(UnicodeScalar(i))
        if iSet.longCharacterIsMember(i) {
            characters = characters + String(c)
        }
    }
    print("characters not in set: \'\(characters)\'")
}
  • 5
    Is no one else completely flabbergasted at how long this code is to do this? I mean that method name is already hell of long, even without choosing the allowed character set. – thatidiotguy Sep 30 '14 at 20:19
  • 24
    No, I favor understandability over short terse naming. Autocomplete takes the pain out. stringByAddingPercentEncodingWithAllowedCharacters() leaves little doubt about what it does. Interesting comment considering how long the word: "flabbergasted" is. – zaph Sep 30 '14 at 20:37
  • 1
    stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) Does not encode all character properly Bryan Chen's answer is a better solution. – Julio Garcia Jan 30 '16 at 16:54
  • 2
    @zaph I added & to character set of URLQueryAllowedCharacterSet and I got each character encoded. Checked with iOS 9, looks like buggy, I went with @bryanchen's answer, it works well !! – Akash Kava Mar 2 '16 at 15:28
  • 3
    The answer below that uses URLComponents and URLQueryItem is much cleaner IMO. – Aaron Brager Nov 12 '17 at 17:05
0

This is working for me in Swift 4.2. The usage case is taking a URL from the clipboard or similar which may already have escaped characters but which also contains Unicode characters which could cause URL(string:) to fail.

func encodedUrl(from string: String) -> URL? {
    // Remove preexisting encoding
    guard let decodedString = string.removingPercentEncoding,
        // Reencode, to revert decoding while encoding missed characters
        let percentEncodedString = decodedString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            // Coding failed
            return nil
    }
    // Create URL from encoded string, or nil if failed
    return URL(string: percentEncodedString)
}

let urlText = "https://www.example.com/폴더/search?q=123&foo=bar&multi=eggs+and+ham&hangul=한글&spaced=lovely%20spam&illegal=<>"
let url = encodedUrl(from: urlText)

Value of url at the end: https://www.example.com/%ED%8F%B4%EB%8D%94/search?q=123&foo=bar&multi=eggs+and+ham&hangul=%ED%95%9C%EA%B8%80&spaced=lovely%20spam&illegal=%3C%3E

Note that both %20 and + spacing are preserved, Unicode characters are encoded, and the %20 in the original urlText is not double encoded.

Caveat: This is a shortcut, as it's using .urlQueryAllowed on the entire URL; it also assumes the URL was already working in a browser. Use wisely! I'm also open to suggestions (I stopped short of chopping the entire URL up with URLComponents, applying individual character sets, and reassembling).

9

Swift 4 (not tested - please comment if it works or not. Thanks @sumizome for suggestion)

var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)

Swift 3

let allowedQueryParamAndKey =  NSCharacterSet.urlQueryAllowed.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)

Swift 2.2 (Borrowing from Zaph's and correcting for url query key and parameter values)

var allowedQueryParamAndKey =  NSCharacterSet(charactersInString: ";/?:@&=+$, ").invertedSet
paramOrKey.stringByAddingPercentEncodingWithAllowedCharacters(allowedQueryParamAndKey)

Example:

let paramOrKey = "https://some.website.com/path/to/page.srf?a=1&b=2#top"
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
// produces:
"https%3A%2F%2Fsome.website.com%2Fpath%2Fto%2Fpage.srf%3Fa%3D1%26b%3D2%23top"

This is a shorter version of Bryan Chen's answer. I'd guess that urlQueryAllowed is allowing the control characters through which is fine unless they form part of the key or value in your query string at which point they need to be escaped.

  • 2
    I like the Swift 3 solution, but it does not work for me in Swift 4: "Cannot use mutating member on immutable value: 'urlQueryAllowed' is a get-only property". – Marián Černý Mar 9 at 20:29
  • @MariánČerný just make the CharacterSet mutable (with var) and then call .remove on it in a second step. – sumizome Sep 25 at 22:45
14

Swift 4

To encode a parameter in URL I find using .alphanumerics character set the easiest option:

let encoded = parameter.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
let url = "http://www.example.com/?name=\(encoded!)"

Using any of the standard Character Sets for URL Encoding (like URLQueryAllowedCharacterSet or URLHostAllowedCharacterSet) won't work, because they do not exclude = or & characters.

Note that by using .alphanumerics it will encode some characters that do not need to be encoded (like -, ., _ or ~ -– see 2.3. Unreserved characters in RFC 3986). I find using .alphanumerics simpler than constructing a custom character set and do not mind some additional characters to be encoded. If that bothers you, construct a custom character set as is described in How to percent encode a URL String, like for example:

var allowed = CharacterSet.alphanumerics
allowed.insert(charactersIn: "-._~") // as per RFC 3986
let encoded = parameter.addingPercentEncoding(withAllowedCharacters: allowed)
let url = "http://www.example.com/?name=\(encoded!)"

Warning: The encoded parameter is force unwrapped. For invalid unicode string it might crash. See Why is the return value of String.addingPercentEncoding() optional?. Instead of force unwrapping encoded! you can use encoded ?? "" or use if let encoded = ....

8

Swift 4:

It depends by the encoding rules followed by your server.

Apple offer this class method, but it don't report wich kind of RCF protocol it follows.

var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

Following this useful tool you should guarantee the encoding of these chars for your parameters:

  • $ (Dollar Sign) becomes %24
  • & (Ampersand) becomes %26
  • + (Plus) becomes %2B
  • , (Comma) becomes %2C
  • : (Colon) becomes %3A
  • ; (Semi-Colon) becomes %3B
  • = (Equals) becomes %3D
  • ? (Question Mark) becomes %3F
  • @ (Commercial A / At) becomes %40

In other words, speaking about URL encoding, you should following the RFC 1738 protocol.

And Swift don't cover the encoding of the + char for example, but it works well with these three @ : ? chars.

So, to correctly encoding each your parameter , the .urlHostAllowed option is not enough, you should add also the special chars as for example:

encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")

Hope this helps someone who become crazy to search these informations.

  • Your implementation is completely wrong. How would a parameter "věž" be encoded? – Marián Černý Mar 9 at 19:38
  • Thank you, I've update my answer. – Alessandro Ornano Mar 10 at 7:37
20

Swift 3:

let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师"

1. encodingQuery:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

result:

"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 

2. encodingURL:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

result:

"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
  • I used first solution but I want to my text back, like iOS开发工程师. – Akshay Phulare Jan 2 at 13:38
  • .urlQueryAllowed worked for me, thanks – Naveed Ahmad Nov 24 at 19:36
36

You can use URLComponents to avoid having to manually percent escape your query string:

let scheme = "https"
let host = "www.google.com"
let path = "/search"
let queryItem = URLQueryItem(name: "q", value: "Formula One")


var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]

if let url = urlComponents.url {
    print(url)   // "https://www.google.com/search?q=Formula%20One"
}

extension URLComponents {
    init(scheme: String, host: String, path: String, queryItems: [URLQueryItem]) {
        self.init()
        self.scheme = scheme
        self.host = host
        self.path = path
        self.queryItems = queryItems
    }
}

if let url = URLComponents(scheme: "https",
                             host: "www.google.com",
                             path: "/search",
                       queryItems: [URLQueryItem(name: "q", value: "Formula One")]).url {

    print(url)  // https://www.google.com/search?q=Formula%20One
}
  • 6
    This answer needs more attention, as there are issues with all of the other ones (though to be fair they may have been best practice at the time). – Asa May 18 '17 at 14:55
  • 1
    Sadly, URLQueryItem does not always encode correctly. For example, Formula+One would be encoded to Formula+One, which would be decoded to Formula One. Therefore be cautious with the plus sign. – Sulthan Mar 10 at 8:15
2

This one is working for me.

func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {

    let unreserved = "*-._"
    let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
    allowed.addCharactersInString(unreserved)

    if plusForSpace {
        allowed.addCharactersInString(" ")
    }

    var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)

    if plusForSpace {
        encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
    }
    return encoded
}

I found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.

4

Had need of this myself, so I wrote a String extension that both allows for URLEncoding strings, as well as the more common end goal, converting a parameter dictionary into "GET" style URL Parameters:

extension String {
    func URLEncodedString() -> String? {
        var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        return escapedString
    }
    static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
        if (parameters.count == 0)
        {
            return nil
        }
        var queryString : String? = nil
        for (key, value) in parameters {
            if let encodedKey = key.URLEncodedString() {
                if let encodedValue = value.URLEncodedString() {
                    if queryString == nil
                    {
                        queryString = "?"
                    }
                    else
                    {
                        queryString! += "&"
                    }
                    queryString! += encodedKey + "=" + encodedValue
                }
            }
        }
        return queryString
    }
}

Enjoy!

  • 2
    This does not encode the '&' sign. Using a '&' in a parameter will f*** up the querystring – Sam Nov 26 '15 at 14:34
  • This is wrong, it does not encode & or = in parameters. Check my solution instead. – Marián Černý Mar 9 at 20:20
32

Swift 3:

let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)

if let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
//do something with escaped string
}
  • 2
    You need to include ` ` (space) in the string of characters – AJP Sep 29 '16 at 15:49
  • 1
    You also need to include ^ – Mani Apr 27 '17 at 6:28
11

Everything is same

var str = CFURLCreateStringByAddingPercentEscapes(
    nil,
    "test/test",
    nil,
    "!*'();:@&=+$,/?%#[]",
    CFStringBuiltInEncodings.UTF8.rawValue
)

// test%2Ftest
  • You didn't .bridgeToOvjectiveC() second argument and didn't get "Cannot convert the expression's type 'CFString!' to type 'CFString!'" ? – Kreiri Jul 3 '14 at 11:16
  • @Kreiri Why it is needed? Both playground and REPL are happy with my code. – Bryan Chen Jul 3 '14 at 11:55
  • Mine aren't :/ (beta 2) – Kreiri Jul 3 '14 at 12:02
  • This is a better answer as it encodes the & correctly. – Sam Nov 26 '15 at 14:34

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.