How to validate an url on the iPhone How to validate an url on the iPhone ios ios

How to validate an url on the iPhone


Why not instead simply rely on Foundation.framework?

That does the job and does not require RegexKit :

NSURL *candidateURL = [NSURL URLWithString:candidate];// WARNING > "test" is an URL according to RFCs, being just a path// so you still should check scheme and all other NSURL attributes you needif (candidateURL && candidateURL.scheme && candidateURL.host) {  // candidate is a well-formed url with:  //  - a scheme (like http://)  //  - a host (like stackoverflow.com)}

According to Apple documentation :

URLWithString: Creates and returns an NSURL object initialized with a provided string.

+ (id)URLWithString:(NSString *)URLString

Parameters

URLString : The string with which to initialize the NSURL object. Must conform to RFC 2396. This method parses URLString according to RFCs 1738 and 1808.

Return Value

An NSURL object initialized with URLString. If the string was malformed, returns nil.


Thanks to this post, you can avoid using RegexKit.Here is my solution (works for iphone development with iOS > 3.0) :

- (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];}

If you want to check in Swift my solution given below:

 func isValidUrl(url: String) -> Bool {        let urlRegEx = "^(https?://)?(www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.[a-z]{2,6}(/[-\\w@\\+\\.~#\\?&/=%]*)?$"        let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)        let result = urlTest.evaluate(with: url)        return result    }


Instead of writing your own regular expressions, rely on Apple's. I have been using a category on NSString that uses NSDataDetector to test for the presence of a link within a string. If the range of the link found by NSDataDetector equals the length of the entire string, then it is a valid URL.

- (BOOL)isValidURL {    NSUInteger length = [self length];    // Empty strings should return NO    if (length > 0) {        NSError *error = nil;        NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];        if (dataDetector && !error) {            NSRange range = NSMakeRange(0, length);            NSRange notFoundRange = (NSRange){NSNotFound, 0};            NSRange linkRange = [dataDetector rangeOfFirstMatchInString:self options:0 range:range];            if (!NSEqualRanges(notFoundRange, linkRange) && NSEqualRanges(range, linkRange)) {                return YES;            }        }        else {            NSLog(@"Could not create link data detector: %@ %@", [error localizedDescription], [error userInfo]);        }    }    return NO;}