2

I am encoding my string to hit a web service. I am using addingPercentEncoding(withAllowedCharacters: CharacterSet) to encode my String.

Everything works fine except the '(apostrophe) character gets encoded to %E2%80%99 instead of %27.

    if let _keyword = keyword?
        .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
        parameters?["keyword"] = _keyword
    }

For Example:

When keyword is Maggie's, output = "Maggie%E2%80%99s" instead of "Maggie%27s".

Output is fine for others, when keyword is Jelly Extracts output is "Jelly%20Extracts".

So, how do I encode '(apostrophe) properly to %27

Edit: When I pass static text, like "Maggie's.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)" output is correct but when I wrap it in a variable output comes incorrect.

Community
  • 1
  • 1
udbhateja
  • 948
  • 6
  • 21
  • 2
    apostrophe(') is a legal character in query. It needn't not or won't be encoded. – Rikesh Subedi Apr 02 '19 at 09:44
  • 2
    For anyone running into this issue because apostrophe encoding doesn't work as expected, you're probably running into Smart Punctuation issues. Smart Punctuation replaces the symbol backtick (') with the apostrophe (’), which are two different characters. The apostrphe (’) encodes to %E2%80%99 whereas the symbol backtick encodes to %27. You can turn smart punctuation off on a per textfield basis via the `smartQuotesType` method. – Alex Sullivan Jan 25 '21 at 14:11
  • @AlexSullivan is correct – Bhavesh Lathigara Sep 07 '22 at 08:54

1 Answers1

0

Instead of urlQueryAllowed use alphanumerics.

let originalString = "Maggie's"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
print(escapedString) // Optional("Maggie%27s")
Daniil Subbotin
  • 6,138
  • 5
  • 20
  • 24