Possible Duplicate:
How to validate an url on the iPhone
In Objective-C, does anyone have a good method to test if a given string appears to be a URL?
Possible Duplicate:
How to validate an url on the iPhone
In Objective-C, does anyone have a good method to test if a given string appears to be a URL?
Do this:
NSURL* url = [NSURL URLWithString:stringToTest];
if (url && url.scheme && url.host)//This comparision never fails
{
//the url is ok
NSLog(@"%@ is a valid URL", yourUrlString);
}
If stringToTest
is indeed an URL then url will be instantiate as expected. Otherwise +[NSURL URLWithString:]
return nil
.
Most methods in Cocoa Touch return nil
on illegal input, very few actually throws an NSInvalidArgumentException
. Each method is documented with what they return on invalid input.
You can use a regular expression. For iPhone 3 and up, you can do it without a framework. Otherwise use RegexKitLite or something.
Here is a regex pattern for checking URLs:
"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
Doing it without a framework:
- (BOOL)validateUrl:(NSString *)candidate {
NSString *urlRegEx =
@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}