Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

The deprecation message says (emphasis mine):

Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

So you only need to supply an adequate NSCharacterSet as argument. Luckily, for URLs there’s a very handy class method called URLHostAllowedCharacterSet that you can use like this:

let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Update for Swift 3 — the method becomes the static property urlHostAllowed:

let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Be aware, though, that:

This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.

Leave a Comment