Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to URL Decode in iOS - Objective C

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

like image 449
VinnyD Avatar asked Oct 27 '11 17:10

VinnyD


2 Answers

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.

like image 194
rob mayoff Avatar answered Nov 19 '22 08:11

rob mayoff


// Decode a percent escape encoded string.
- (NSString*) decodeFromPercentEscapeString:(NSString *) string {
return (__bridge NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                        (__bridge CFStringRef) string,
                                                        CFSTR(""),
                                                        kCFStringEncodingUTF8);
} 

http://cybersam.com/ios-dev/proper-url-percent-encoding-in-ios

This seems to be the preferred way because... "Apparently" this is a "bug" apple is aware of, but they haven't done anything about it yet... ( http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/ )

like image 20
delux247 Avatar answered Nov 19 '22 08:11

delux247