URL Encoding in Objective-C

The NSString class contains a method stringByAddingPercentEscapesUsingEncoding which returns a URL-encoded string. Problem is, the method seems to provide support for percent escapes on just a few characters.

Below is a category extension to the NSString class that uses the method CFURLCreateStringByAddingPercentEscapes in the CFURL class to handle a more complete set of characters for encoding. By using a category (versus a standalone method in a class) we are essentially adding a new method for encoding to all NSString objects.

Define the NSString Encoding Category

The begin, create an interface definition for NSString and add a category name inside a set of parenthesis after the interface declaration. Save the file with the name NSString+Encode.h

//  NSString+Encode.h
@interface NSString (encode)
- (NSString *)encodeString:(NSStringEncoding)encoding;
Implementation of the NSString Encoding Category

Create a new file with the code below and save in a file with the name NSString+Encode.m.

//  NSString+Encode.m
@implementation NSString (encode)
- (NSString *)encodeString:(NSStringEncoding)encoding
  return (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self,
      NULL, (CFStringRef)@";/?:@&=$+{}<>,",
Using the New NSString Encoding Method

The code below shows how one might call the new method:

#import "NSString+Encode.h"
// Create a new string
NSString *urlParams = @"submit?param=1&url=newsite.com&title=Post title";
// Encode the parameters
NSString *encodedStr = [urlParams encodeString:NSUTF8StringEncoding];
NSLog(@"\nOriginal: %@\nEncoding 1: %@\nEncoding 2: %@", 
    [urlParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],

Below is the output of the original string, the encoded string using stringByAddingPercentEscapesUsingEncoding and the output of the new encoding method:

Original: submit?param=1&url=newsite.com&title=Post title
Encoding 1: submit?param=1&url=newsite.com&title=Post%20title
Encoding 2: submit%3Fparam%3D1%26url%3Dnewsite.com%26title%3DPost%20title

  1. Thanks for this. Was very useful and worked :)

Comments are closed.