views:

624

answers:

3

In an application that I'm writing I have some code like this:

NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";

NSURL* url = [NSURL URLWithString:myurl];

[ws openURL:url];

The main difference being that myurl comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning nil.

What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?

+1  A: 

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.

Matt Sheppard
+6  A: 

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:

amrox
A: 

Thanks for your swift responses!

@amrox: I'm sure I tried this earlier and that it encoded the slashes and colons too, but I think I must have been having a senior moment as I tried it just now and it works just fine.

@Matt Sheppard: you're right, technically this is the correct behaviour. Indeed, escaping the URL might not do the right thing (whatever right is), however I feel that opening nearly the correct URL is likely better than an error message.

Stephen Darlington