Meltemi
Meltemi

Reputation: 38349

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!?!

Upvotes: 10

Views: 16117

Answers (3)

Thomas Desert
Thomas Desert

Reputation: 1346

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;
}

Upvotes: 23

s1mm0t
s1mm0t

Reputation: 6095

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"];
}

Upvotes: 8

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

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.

Upvotes: 43

Related Questions