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

1 Answer 1

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 @""; } 
Sign up to request clarification or add additional context in comments.

4 Comments

Anyone understand why? This works very well, but why stringByAddingPercentEscapesUsingEncoding: does not sometimes?
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: stackoverflow.com/questions/6822473/correct-bridging-for-arc
@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.
This is deprecated since iOS 9.0. Apple offers to use stringByAddingPercentEncodingWithAllowedCharacters: instead (which is available since iOS 7.0)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.