2012-01-05 101 views
0

如何检测它是Web URL还是路径?检测路径中的URL

在NSURL苹果参考页面已经写的,它接受一个URL,如果它是基于标准的,但任何一种字符串,它接受一个URL,这样的代码:

NSURL *url=[NSURL URLWithString:@"/book.xml"]; 

    NSLog(@"%@",url); 

这不是一个网页网址,但它拥有它,也将其作为其价值返回。 我已经试过这个功能,它的工作原理,但不是所有的网址!

-(BOOL) urlIsValiad: (NSString *) url { 

    NSString *regex = @"((?:http|https)://(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}/?(?:[\\w\\d\\-./_]+)?)"; 

    NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 

    if ([regextest evaluateWithObject: url] == YES) { 
     NSLog(@"It is a valid URL!"); 
    } else { 
     NSLog(@"It is not valid URL!"); 
    } 


    return [regextest evaluateWithObject:url]; 

} 

我担心的是检测其他路径中的URL!

回答

0
+0

我编辑了我的帖子,我用了一些类似的东西,但即使它有一些例外情况不起作用。 – user1095058 2012-01-05 07:24:18

+0

你确定NSDataDetector不起作用吗?我可能误解了,但NSDataDetector应该能够在一个长字符串中找到多个URL。 – 2012-01-05 07:30:14

+0

不幸的是我不能使用它!因为我打算提供一个适用于OSX版本10.5的应用程序! – user1095058 2012-01-05 14:54:21

0

如何NSDataDetector

NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it."; 
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; 
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])]; 

for (NSTextCheckingResult *match in matches) 
{ 
    if ([match resultType] == NSTextCheckingTypeLink) 
    { 
    NSURL *url = [match URL]; 
    NSLog(@"found URL: %@", url); 
    } 
} 

这样你就不必依赖不可靠的正则表达式,如苹果升级他们的链接检测代码,你可以免费获得这些改进。

+0

不幸的是我不能使用它!因为我打算提供一个从10.5开始的应用程序! – user1095058 2012-01-05 07:50:52

+0

啊,对不起,没有意识到! – 2012-01-05 21:06:14