By MegaCookie

2014-07-03 10:56:02 8 Comments

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(
                        kCFStringEncodingUTF8 );

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


@Mohsin Khubaib Ahmed 2020-06-29 14:20:22

What helped me was that I created a separate NSCharacterSet and used it on an UTF-8 encoded string i.e. textToEncode to generate the required result:

var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&?,:;@+=$*()")
let utfedCharacterSet = String(utf8String: textToEncode.cString(using: .utf8)!)!
let encodedStr = utfedCharacterSet.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let paramUrl = "\(escapedStr)"

@Leo Dabus 2017-04-27 21:27:38

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

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

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

if let url = urlComponents.url {
    print(url)   // ""

extension URLComponents {
    init(scheme: String = "https",
         host: String = "",
         path: String = "/search",
         queryItems: [URLQueryItem]) {
        self.scheme = scheme = host
        self.path = path
        self.queryItems = queryItems

let query = "Formula One"
if let url = URLComponents(queryItems: [URLQueryItem(name: "q", value: query)]).url {
    print(url)  //

@Asa 2017-05-18 14:55:55

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).

@Sulthan 2018-03-10 08:15:58

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.

@Jenel Ejercito Myers 2020-01-23 19:28:09

None of these answers worked for me. Our app was crashing when a url contained non-English characters.

 let unreserved = "-._~/?%$!:"
 let allowed = NSMutableCharacterSet.alphanumeric()
     allowed.addCharacters(in: unreserved)

 let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)

Depending on the parameters of what you are trying to do, you may want to just create your own character set. The above allows for english characters, and -._~/?%$!:

@Hardik Thakkar 2019-11-13 06:39:33

For Swift 5 to endcode string

func escape(string: String) -> String {
    let allowedCharacters = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":=\"#%/<>[email protected]\\^`{|}").inverted) ?? ""
    return allowedCharacters

How to use ?

let strEncoded = self.escape(string: "")
print("escapedString: \(strEncoded)")

@CartoonChess 2018-11-06 17:18:13

This is working for me in Swift 5. 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 URLComponents or URL(string:) to fail.

First, create a character set that includes all URL-legal characters:

extension CharacterSet {

    /// Characters valid in at least one part of a URL.
    /// These characters are not allowed in ALL parts of a URL; each part has different requirements. 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 {
        // Start by including hash, which isn't in any set
        var characters = CharacterSet(charactersIn: "#")
        // All URL-legal characters

        return characters

Next, extend String with a method to encode URLs:

extension String {

    /// Converts a string to a percent-encoded URL, including Unicode characters.
    /// - Returns: An encoded URL if all steps succeed, otherwise nil.
    func encodedUrl() -> URL? {        
        // Remove preexisting encoding,
        guard let decodedString = self.removingPercentEncoding,
            // encode any Unicode characters so URLComponents doesn't choke,
            let unicodeEncodedString = decodedString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters),
            // break into components to use proper encoding for each part,
            let components = URLComponents(string: unicodeEncodedString),
            // and reencode, to revert decoding while encoding missed characters.
            let percentEncodedUrl = components.url else {
            // Encoding failed
            return nil

        return percentEncodedUrl


Which can be tested like:

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

Value of url at the end:

Note that both %20 and + spacing are preserved, Unicode characters are encoded, the %20 in the original urlText is not double encoded, and the anchor (fragment, or #) remains.

Edit: Now checking for validity of each component.

@Leo Dabus 2020-06-28 05:01:46

@jaskiratjd 2019-03-05 11:05:19

let Url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

@ajzbc 2019-02-21 20:54:13

Swift 4.2

A quick one line solution. Replace originalString with the String you want to encode.

var encodedString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)

Online Playground Demo

@Rakshitha Muranga Rodrigo 2020-03-11 22:44:55

This worked thanks: you can check and try decode and encode results on.

@zaph 2014-07-03 11:05:01

Swift 3

In Swift 3 there is addingPercentEncoding

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)



Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

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



The following are useful (inverted) character sets:

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

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:"=\"#%/<>[email protected]\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")



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)\'")

@MegaCookie 2014-07-03 17:44:17

And if I want to add the equal sign too?

@zaph 2014-07-05 03:51:28

Add a custom character set, I added an example.

@thatidiotguy 2014-09-30 20:19:35

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.

@zaph 2014-09-30 20:37:18

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.

@Julio Garcia 2016-01-30 16:54:25

stringByAddingPercentEncodingWithAllowedCharacters(.URLHostA‌​llowedCharacterSet()‌​) Does not encode all character properly Bryan Chen's answer is a better solution.

@zaph 2016-01-30 16:58:53

@JulioGarcia either pick a character set based on the portion of the URL you are using or create a custom character set that matches your needs. Look at the customAllowedSet example.

@Julio Garcia 2016-01-30 17:01:50

Thanks Zaph, I just noticed that function it's been deprecated in iOS 9

@Akash Kava 2016-03-02 09:25:59

@zaph What about &?

@zaph 2016-03-02 13:05:35

@AkashKava pick a character set that meets your needs of use charactersInString: to create a custom character set.

@Akash Kava 2016-03-02 15:28:58

@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 !!

@user3246173 2016-05-19 16:25:09

Why is Apple putting this method in the String class and not on NSURL?

@zaph 2016-05-19 21:34:51

That the method takes a string and returns a string is my best guess.

@Ben Carroll 2016-06-27 06:36:59

And of course, they've cleaned up the API a bit now. For example: let myEncodedString = myString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

@Konstantinos Natsios 2016-10-04 15:22:56

Your code doesn't encode ! and some other special chacacters... why?

@zaph 2016-10-04 15:36:05

Apple supplies several charactersets directed toward URL encoding. If you need to encode a different characterset than those supplied by Apple use the example of customAllowedSet.

@Aaron Brager 2017-11-12 17:05:25

The answer below that uses URLComponents and URLQueryItem is much cleaner IMO.

@Jack 2018-03-23 11:15:32

I used CharacterSet(charactersIn: "=&").inverted Thanks @zaph

@karthikeyan 2020-02-20 13:52:45

Is it possible to back to test/test after conversion?

@Vrushal Raut 2019-01-18 06:55:39


Sometimes this happened just because there is space in slug OR absence of URL encoding for parameters passing through API URL.

let myString = self.slugValue
                let csCopy = CharacterSet(bitmapRepresentation: CharacterSet.urlPathAllowed.bitmapRepresentation)
                let escapedString = myString!.addingPercentEncoding(withAllowedCharacters: csCopy)!
                //always "info:hello%20world"

NOTE : Don't forget to explore about bitmapRepresentation.

@AJP 2016-09-29 10:16:23

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


let paramOrKey = ""
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
// produces:

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.

@Marián Černý 2018-03-09 20:29:19

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".

@sumizome 2018-09-25 22:45:46

@MariánČerný just make the CharacterSet mutable (with var) and then call .remove on it in a second step.

@FD_ 2019-09-14 11:17:37

I believe this and most other solutions have issues when applying the method twice, eg when including an URL with encoded params in another URL's parameters.

@AJP 2019-09-21 11:35:17

@FD_ do you know or do you just have a hunch? Can you experiment with it and post back? Would be good to include this info if so. Thank you.

@FD_ 2019-09-21 12:29:59

@AJP I just tested all your snippets. Swift 3 and 4 work fine, but the one for Swift 2.2 doesn't properly encode %20 as %2520.

@Marián Černý 2018-03-12 08:56:23

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 = "\(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 = "\(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 = ....

@Dion 2019-12-02 14:32:01

.aphanumerics did the trick, thank you! All the other character sets didn't escape the &'s which caused problems when using the strings as get parameters.

@Alessandro Ornano 2018-03-07 10:07:55

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.

@Marián Černý 2018-03-09 19:38:50

Your implementation is completely wrong. How would a parameter "věž" be encoded?

@iHTCboy 2017-04-28 14:34:45

Swift 3:

let originalString = "开发工程师"

1. encodingQuery:

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



2. encodingURL:

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



@Akshay Phulare 2018-01-02 13:38:33

I used first solution but I want to my text back, like iOS开发工程师.

@Sulthan 2019-01-03 14:18:43

Using urlHostAllowed for encoding query parameters in incorrect because it won't encode ?, = and +. When encoding query parameters, you have to encode parameter name and value separately and correctly. This won't work in a general case.

@Bharath 2019-01-06 10:31:05

@Sulthan.. Did you find any solution / alternative for urlHostAllowed

@Sulthan 2019-01-06 10:44:46

@Bharath Yes, you have to build a character set by yourself, e.g. or just use URLComponents.

@SoftDesigner 2020-04-20 15:29:46

URLComponents don't encode the + char too. So the only option is to do it manually: CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charac‌​tersIn: "+"))

@Gaurav Singla 2016-06-06 09:23:08

This one is working for me.

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

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

    if plusForSpace {
        allowed.addCharactersInString(" ")

    var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)

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

I found above function from this link:

@BadPirate 2015-01-02 00:39:59

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 = "?"
                        queryString! += "&"
                    queryString! += encodedKey + "=" + encodedValue
        return queryString


@Sam 2015-11-26 14:34:46

This does not encode the '&' sign. Using a '&' in a parameter will f*** up the querystring

@Marián Černý 2018-03-09 20:20:18

This is wrong, it does not encode & or = in parameters. Check my solution instead.

@Hong Wei 2016-09-29 10:34:54

Swift 3:

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

if let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
//do something with escaped string

@AJP 2016-09-29 15:49:35

You need to include ` ` (space) in the string of characters

@Mani 2017-04-27 06:28:58

You also need to include ^

@Bryan Chen 2014-07-03 11:05:13

Everything is same

var str = CFURLCreateStringByAddingPercentEscapes(

// test%2Ftest

@Kreiri 2014-07-03 11:16:55

You didn't .bridgeToOvjectiveC() second argument and didn't get "Cannot convert the expression's type 'CFString!' to type 'CFString!'" ?

@Bryan Chen 2014-07-03 11:55:20

@Kreiri Why it is needed? Both playground and REPL are happy with my code.

@Kreiri 2014-07-03 12:02:31

Mine aren't :/ (beta 2)

@Sam 2015-11-26 14:34:05

This is a better answer as it encodes the & correctly.

Related Questions

Sponsored Content

17 Answered Questions

[SOLVED] How do I call Objective-C code from Swift?

  • 2014-06-02 20:05:42
  • David Mulder
  • 289397 View
  • 980 Score
  • 17 Answer
  • Tags:   objective-c swift

10 Answered Questions

[SOLVED] Java URL encoding of query string parameters

28 Answered Questions

[SOLVED] How do I make an attributed string using Swift?

20 Answered Questions

[SOLVED] #pragma mark in Swift?

  • 2014-06-03 14:05:56
  • Arbitur
  • 223733 View
  • 940 Score
  • 20 Answer
  • Tags:   swift documentation

33 Answered Questions

[SOLVED] Loading/Downloading image from URL on Swift

8 Answered Questions

[SOLVED] How to URL encode a string in Ruby

7 Answered Questions

[SOLVED] URL encoding in Android

25 Answered Questions

[SOLVED] HTTP URL Address Encoding in Java

  • 2009-04-07 03:28:22
  • suDocker
  • 368453 View
  • 366 Score
  • 25 Answer
  • Tags:   java http urlencode

13 Answered Questions

[SOLVED] URL Encoding using C#

  • 2009-02-22 18:48:23
  • masfenix
  • 602099 View
  • 342 Score
  • 13 Answer
  • Tags:   c# .net urlencode

5 Answered Questions

[SOLVED] When to encode space to plus (+) or %20?

  • 2010-04-20 20:55:31
  • Muhammad Hewedy
  • 245320 View
  • 490 Score
  • 5 Answer
  • Tags:   urlencode

Sponsored Content