1

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. 
Alex Pelletier
  • 4,933
  • 6
  • 34
  • 58

3 Answers3

8

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
Community
  • 1
  • 1
Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
3

you should use the ASCII value of "|" :i.e %7C. You can not directly use these types of special characters.

    NSURL *url = [[NSURL alloc] initWithString:@"http://google.com?id=%7Ctest%7C"];

i hope it will works.

Rameshwar Gupta
  • 791
  • 7
  • 21
2

The reason it doesn't work is because those are not directly legal characters for a URL.

This is taken from a brilliant answer to an (in effect) related Question on SO: Which characters make a URL invalid?

"In general URLs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=. Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word."

However in practice, you shouldn't really use commas or square brackets or funky things in a URL - you don't know which browsers will deal with it properly or not. There is absolutely no good reason to use any funky characters in a URL - even if it is a URL to a local file.

Yes, using NSURL URLWithString is a better policy for Objective-C, but the main thing to do is stick to the dos and don'ts of URLs.

Community
  • 1
  • 1
Benjamin R
  • 555
  • 6
  • 25