Skip to content

Instantly share code, notes, and snippets.

@crespoxiao
Created October 21, 2016 03:34
Show Gist options
  • Save crespoxiao/b3ff8014d14b467a18a5f1394653c2cc to your computer and use it in GitHub Desktop.
Save crespoxiao/b3ff8014d14b467a18a5f1394653c2cc to your computer and use it in GitHub Desktop.
validate url
#import <Foundation/Foundation.h>
@interface NSString (CFXValidateURL)
- (BOOL)cfx_validateUrl;
- (BOOL)cfx_validateUrl_RegEx;
@end
#import "NSString+CFXValidateURL.h"
@implementation NSString (CFXValidateURL)
- (BOOL)cfx_validateUrl {
NSUInteger length = [self length];
if (length) {
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;
}
}
}
return NO;
}
- (BOOL)cfx_validateUrl_RegEx {
NSPredicate *websitePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
@"^(((((h|H)(t|T){2}(p|P)s?)|((f|F)(t|T)(p|P)))://(w{3}.)?)|(w{3}.))[A-Za-z0-9]+(.[A-Za-z0-9-:;\?#_]+)+"];
if ([websitePredicate evaluateWithObject:self]){
return YES;
}
return NO;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment