How to URL Decode in iOS - Objective C

VinnyD picture VinnyD · Oct 27, 2011 · Viewed 36k times · Source

The stringByReplacingPercentEscapesUsingEncoding method is not working properly as it's not decoding special symbols that dont start with a % character, i.e., the + character. Does anyone know of a better method to do this in iOS?

Here's what I'm currently using:

NSString *path = [@"path+with+spaces"
     stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

And here's an example of the output:

path+with+spaces

Answer

rob mayoff picture rob mayoff · Oct 27, 2011
NSString *path = [[@"path+with+spaces"
    stringByReplacingOccurrencesOfString:@"+" withString:@" "]
    stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Note that the plus-for-space substitution is only used in application/x-www-form-urlencoded data - the query string part of a URL, or the body of a POST request.