Opening a non-standard URL in a Cocoa app

I'm not sure if this is exactly what you're looking for, but there is a method in NSString that will sanitize a URL:

stringByAddingPercentEscapesUsingEncoding:


I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two hex characters to follow it).

You can't just URL encode the URL as given to you, because that would encode the /s and ?s as well, which you don't want.

So, the question is, what's the correct behaviour here?

Perhaps you would want it to be turned into...

http://www.somewebsite.com/method?a=%25d

(i.e. the % is encode to the encoded version of % in a URL, so when method gets the input, it sees a as being set to %d)

I don't think there's any library function which will do that sort of thing for you, since there's no 'correct' way to do it. About he only correct thing you can do is return an error message saying the URL you were given is invalid (just as URLWithString is)


If you wanted to try to handle the input, I guess you would need to search the URL for any % symbols which are not immediately followed by two hex characters, and then replace the % with %25 in that case. That should be quite possible with a regular expression, though I suspect there may be some additional complexities if your URLs start containing encoded versions of characters outside the ASCII character set.