Objective-C: How to determine the http address in a string?

Suppose I have a line:

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

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

+7
source share
2 answers

You can use NSDataDetectors . They were added in iOS4 and are very useful. You want to create a data detector using NSTextCheckingTypeLink and let it do it.

 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); 
+24
source

You can do something like:

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

All Articles