Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String won't url encode in iOS

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];
like image 551
JoeCortopassi Avatar asked Feb 08 '12 03:02

JoeCortopassi


People also ask

What is the best way to URL encode a string?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

How do you add %20 to a URL?

Spaces are not allowed in URLs. They should be replaced by the string %20. In the query string part of the URL, %20 can be abbreviated using a plus sign (+).

What is %20 in the URL?

A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.


1 Answers

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 @"";
}
like image 85
JoeCortopassi Avatar answered Sep 19 '22 14:09

JoeCortopassi