Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Created March 26, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evgeniyd/b35097bad451c59e23b1 to your computer and use it in GitHub Desktop.
Save evgeniyd/b35097bad451c59e23b1 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface NSString (URLValidation)
- (BOOL)isValidURL;
@end
#import "NSString+URLValidation.h"
@implementation NSString (URLValidation)
- (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;
}
@end
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "NSString+URLValidation.h"
@interface NSString_URLValidationTests : XCTestCase
@end
@implementation NSString_URLValidationTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
//////////////////////////////////////////////////////////////////////////////
#pragma mark ---- Validation Tests
//////////////////////////////////////////////////////////////////////////////
- (void)testIsValidURL {
// wrong formats
NSString* testString = nil;
XCTAssertFalse([testString isValidURL], @"'nil' string is not a valid URL");
testString = @"";
XCTAssertFalse([testString isValidURL], @"'empty' string is not a valid URL");
testString = @"about:blank";
XCTAssertFalse([testString isValidURL], @"'about:page' string is not a valid URL");
// correct formats
testString = @"http://example.com";
XCTAssertTrue([testString isValidURL]);
testString = @"https://example.com";
XCTAssertTrue([testString isValidURL]);
testString = @"https://igcdn-photos-d-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11049325_454620968038899_1613081310_n.jpg";
XCTAssertTrue([testString isValidURL]);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment