skip to Main Content

I have two strings encoded differently for spacing:

let first = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test"
let second = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New%20calendar%20test"

let firstOutput = first.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test
let secondOutput = second.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New calendar test
  1. Why doesn’t it remove encoding correctly, since + is a correct encoding for space?

  2. How can I correctly decode both of them, no matter which one I receive?

2

Answers


  1. If you could decode a whitespace from two different patters, then when you wanted to do the opposite and encode it which one it should take?

    That’s the reason why removingPercentEncoding only supports one of them.

    Login or Signup to reply.
  2. “Why” is a difficult question to answer except for the people who had a hand in implementing CFURLCreateStringByReplacingPercentEscapes. The fact is that it doesn’t.

    I can speculate that it doesn’t because the + for space replacement is not part of RFC 3986: Uniform Resource Identifier (URI): Generic Syntax. It should only be used in the query part of the URL, which is of type application/x-www-form-urlencoded. But this is just my guess.

    Anyway, if you want to convert + to space, you should do so before performing percent-decoding, lest you decode %2b into + and then further decode it into a space, leaving no way for your URL to contain a genuine + after decoding.

    let firstOutput = first
        .replacingOccurrences(of: "+", with: " ")
        .removingPercentEncoding
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search