Encoding a URL in iOS 9

The typical way to encode URLs (e.g. turn spaces into %20) was to use NSString’s

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

As you may have noticed, that method has been deprecated in iOS 9. You now need to use

stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet

which takes an NSCharacterSet as it’s argument. What NSCharacterSet am I supposed to use you may ask. I recently ran into this and found the following worked for me:

[NSCharacterSet URLFragmentAllowedCharacterSet]

The relevant Apple documentation can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *