Search code examples
iosobjective-cxcodensurlnon-ascii-characters

Objective-C NSURL With Non-Alphabetical Characters


I am trying to create an NSURL with special characters like " ","|","-",":", etc. If I have any of these characters in my string the NSURL does not init. What can I do to create an NSURL with these characters? The following does not work:

NSURL *url = [[NSURL alloc] initWithString:@"http://google.com?id=|test|"]; //if i remove the | it works. 

Solution

  • Problem Description

    From the documentation of [NSURL initWithString]

    Initializes an NSURL object with a provided URL string.

    - (id)initWithString:(NSString *)URLString

    Parameters - URLString

    The URL string with which to initialize the NSURL object. This URL string must conform to URL format as described in RFC 2396, and must not be nil. This method parses URLString according to RFCs 1738 and 1808.

    Return Value

    An NSURL object initialized with URLString. If the URL string was malformed, returns nil.

    Discussion

    This method expects URLString to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding.

    Solution

    You need to encode the string as url first. One of the solutions for this is to use [NSString stringByAddingPercentEscapesUsingEncoding:][1]

    There are other discussion on Stackoverflow about encoding strings to urls:

    1. iOS : How to do proper URL encoding?
    2. How do I URL encode a string