iPhone tip #1 – URL encoding in Objective-C


If you are n00b when it comes to iPhone development, then you’ve come to the right place! We’ll be posting howtos, tips and tricks continuously.

So, how do you URL enconde a string? It’s quite simple if you know how. :)

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

To create an URL object, do like this:

[NSURL URLWithString:encodedUrlString]

, , , , , , ,

  1. #1 by Peter Strömberg on April 8, 2009 - 23:06

    Ah, an iPhone category. Nice! Could someone explain to me why encoding is such a tricky subject? =)

  2. #2 by onitake on April 27, 2009 - 17:55

    unfortunately, this will not correctly escape characters reserved as uri part delimiters or sub-part delimiters.
    if you want to do that roll your own converter or use CFURLCreateStringByAddingPercentEscapes instead. as you might already know, corefoundation is toll-free bridged to foundation, so you can just cast between cfstring and nsstring. but don’t forget to release/autorelease.

    example:
    NSString *encodedString = (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) unencodedString, NULL, NULL, kCFStringEncodingUTF8);

    if you want to make it rfc 3986-safe, use the following code:
    CFStringRef escapeChars = (CFStringRef) @”:/?#[]@!$&’()*+,;=”;NSString *encodedString = (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) unencodedString, NULL, escapeChars, kCFStringEncodingUTF8);

  3. #3 by Samuel on April 27, 2009 - 21:09

    Thanks, that’s correct! I have edited the post!

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

  4. #4 by Dan J on August 26, 2009 - 19:02

    I think you need to include ” in the list of escaped characters. Don’t forget to escape it in code, e.g.

    CFSTR(”:/?#[]@!$&’()*+,;=\””)

    http://en.wikipedia.org/wiki/Percent-encoding

    This was very useful – thanks!

  5. #5 by sugiarto on November 23, 2009 - 23:56

    Thanks,
    very help me..

  6. #6 by me on June 16, 2010 - 09:38

    be sure to replace the ” with regular quotes when copy & paste this function … otherwise the compiler will get an error …

(will not be published)

Additional comments powered by BackType