Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Sheehan Alam Avatar asked Aug 10 '11 16:08

Sheehan Alam


2 Answers

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);
like image 200
Joshua Weinberg Avatar answered Nov 07 '22 20:11

Joshua Weinberg


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];
}
like image 44
FreeAsInBeer Avatar answered Nov 07 '22 21:11

FreeAsInBeer