"stringByAddingPercentEncodingWithAllowedCharacters" replaces more characters than it should

1.4k views Asked by At

Playing around with Swift I came across something I do not understand.

The following code replaces not only the /% characters as intended, it also replaces the ä character:

immport Foundation

extension String{
    func encode() -> String{
        let customAllowedSet =  NSCharacterSet(charactersInString:"/%").invertedSet
        return self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)!
    }
}

let testStr = "Ein String der % und / enthält"
// contains what is expected

let percentEncodedStr = testStr.encode()
// contains "Ein String der %25 und %2F enth%C3%A4lt"

let decodedStr = percentEncodedStr.stringByRemovingPercentEncoding
// contains what was in testStr originally 

Why is the ä replaced by %C3%A4?

1

There are 1 answers

0
Ken Thomases On BEST ANSWER

That method is for encoding components or subcomponents of URLs. No non-ASCII characters are ever allowed in URLs. They are always encoded.

The docs for stringByAddingPercentEncodingWithAllowedCharacters() say:

Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.

That is, no non-ASCII characters are ever considered to be "allowed".