I am trying to build a homebrew web brower to get more proficient at Cocoa. I need a good way to validate whether the user has entered a valid URL. I have tried some regular expressions but NSString has some interesting quirks and doesn't like some of the back-quoting that most regular expressions I've seen use.
views:
767answers:
2
+4
A:
You could start with the + (id)URLWithString:(NSString *)URLString
method of NSURL
, which returns nil
if the string is malformed.
If you need further validation, you can use the baseURL
, host
, parameterString
, path
, etc methods to give you particular components of the URL, which you can then evaluate in whatever way you see fit.
Jon Shea
2008-10-10 21:57:35
Thanks, worked perfectly!
mclaughlinj
2008-10-10 22:36:00
+2
A:
I've found that it is possible to enter some URLs that seem to be OK but are rejected by the NSURL creation methods. So we have a method to escape the string first to make sure it's in a good format. Here is the meat of it:
NSString *escapedURLString = NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)URLString, (CFStringRef)@"%+#", // Characters to leave unescaped NULL, kCFStringEncodingUTF8));
danwood
2008-10-10 23:45:07