Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString method to percent escape '&' for URL

Which NSString encoding method will percent escape the ampersand (&) character correctly into %26?

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

gets the spaces (%20) and other baddies but ignores ampersands!?!

like image 837
Meltemi Avatar asked Jan 29 '10 01:01

Meltemi


3 Answers

Ampersands won't be processed by that method because they're legal characters in a URL. You should probably pre-process particularly problematic pieces, piecemeal, prior to this call.

like image 130
Ben Gottlieb Avatar answered Oct 31 '22 18:10

Ben Gottlieb


Here is a nice solution to this problem taken from Bagonca blog to url-encode your NSStrings :

+ (NSString *)urlEncodeValue:(NSString *)str
{
   NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
   return [result autorelease];
}

Add CFBridgingRelease( for ARC compatibility.

+ (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8));
    return result;
}
like image 40
Thomas Desert Avatar answered Oct 31 '22 16:10

Thomas Desert


The accepted answer isn't quite right I don't think, you need to process the string after calling addPercentEscapesAndReplaceAmpersand

+ (NSString *) addPercentEscapesAndReplaceAmpersand: (NSString *) stringToEncode
{
    NSString *encodedString = [stringToEncode stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; 
    return [encodedString stringByReplacingOccurrencesOfString: @"&" withString: @"%26"];
}
like image 45
s1mm0t Avatar answered Oct 31 '22 18:10

s1mm0t