Sheehan Alam
Sheehan Alam

Reputation: 60859

Objective-C: How can I detect http URL's in a string?

Let's assume I have the string:

"I love visiting http://www.google.com"

How can I detect the token, http://www.google.com?

Upvotes: 7

Views: 6586

Answers (2)

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

You can use NSDataDetectors These were added in iOS4 and are quite useful. You want to create a data detector with the NSTextCheckingTypeLink and let it do its thing.

NSString *testString = @"Hello http://google.com world";
NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detect matchesInString:testString options:0 range:NSMakeRange(0, [testString length])];
NSLog(@"%@", matches);

Upvotes: 26

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

You could do something like:

-(BOOL)textIsUrl:(NSString*)someString {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES ^[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?$"];

    [predicate evaluateWithObject:someString];
}

Upvotes: 1

Related Questions