9

I'm seriously having a brain fart here, but I can't figure out why this isn't encoding for the life of me. Been searching all over, and I can't even get the code samples to encode. Any ideas?

NSString *searchString = @"waffl&es";

NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:@"http://en.wikipedia.org/?search=%@", encodedSearchString];
NSURL *url = [NSURL URLWithString:urlString];
JoeCortopassi
  • 5,083
  • 7
  • 37
  • 65

1 Answers1

25

For future reference, this is what I found to work (i.e. encode everything properly)

+ (NSString*)encodeURL:(NSString *)string
{
    NSString *newString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

    if (newString) 
    {
        return newString;
    }

    return @"";
}
JoeCortopassi
  • 5,083
  • 7
  • 37
  • 65
  • 2
    Anyone understand why? This works very well, but why stringByAddingPercentEscapesUsingEncoding: does not sometimes? – Carlos Ricardo Jul 19 '12 at 21:34
  • 4
    The bridging cast you are using in this answer is incorrect, and will cause a memory leak. You should be using '__bridge_transfer' for the result. See this question for more info: http://stackoverflow.com/questions/6822473/correct-bridging-for-arc – Nate Petersen Jan 07 '13 at 19:08
  • @CarlosRicardo stringByAddingPercentEscapesUsingEncoding: is intended to only escape characters that are not legal URL characters. "&" is a legal URL character, therefore it is not escaped. If you want to include "&" in a query parameter, however, you need to use this code instead to make sure it gets escaped. – bugloaf Mar 05 '15 at 17:54
  • 1
    This is deprecated since iOS 9.0. Apple offers to use `stringByAddingPercentEncodingWithAllowedCharacters:` instead (which is available since iOS 7.0) – ReDetection Feb 10 '16 at 04:30