2015-08-08 87 views
2

我如何检查NSURL是否有效? 1)如果我输入“facebook.com”,则应添加“http://www”。如何检查有效的网址?

2)如果我输入 “www.facebook.com”,那么就应该添加的 “http://”

3)如果我输入 “脸谱”,那么它应该在谷歌搜索。

我怎么能做到这一点?

我按照以下方法操作,但不起作用。它始终是第三种情况返回true。(“http://www.facebook”)

if (![url.absoluteString.lowercaseString hasPrefix:@"http://"]) 
    { 
     if(![url.absoluteString.lowercaseString hasPrefix:@"www."]) 
     { 
      url = [NSURL URLWithString:[@"http://www." stringByAppendingString:locationField.text]]; 

     } 
     else 
     { 
      url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]]; 
     } 
    } 
if(![self validateUrl:url.absoluteString]) 
{ 
    url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@",[locationField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; 
} 


- (BOOL) validateUrl:(NSString *)candidate 
{ 
    NSString *urlRegEx = @"((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"; 
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate]; 
} 
+0

添加的NSLog这个url.absoluteString,结果 – Walucas

+0

您的逻辑是不正确粘贴。对于URL“facebook”,您最终将其更改为“http:// www.facebook”,然后对其进行验证。 – rmaddy

+0

@Walucas nslog = absoluteString = http://www.facebook – Rox

回答

5

没有必要添加www.如果用户输入facebook.comhttp://就足够了。反正下面的函数可以吃有或没有www.

func checkURL(url: String) -> Bool {  
    let urlRegEx = "^http(?:s)?://(?:w{3}\\.)?(?!w{3}\\.)(?:[\\p{L}a-zA-Z0-9\\-]+\\.){1,}(?:[\\p{L}a-zA-Z]{2,})/(?:\\S*)?$" 
    let urlTest = NSPredicate(format: "SELF MATCHES %@", urlRegEx) 
    return urlTest.evaluateWithObject(url) 
} 

checkURL("http://www.россия.рф/") // true 
checkURL("http://www.facebook.com/") // true 
checkURL("http://www.some.photography/") // true 
checkURL("http://facebook.com/") // true 

checkURL("http://www.россия/") // false 
checkURL("http://www.facebook/") // false 
checkURL("http://www.some/") // false 
checkURL("http://facebook/") // false 

checkURL("http://россия.рф/") // true 
checkURL("http://facebook.com/") // true 
checkURL("http://some.photography/") // true 
checkURL("http://com/") // false 
+1

您在结尾处假设2或3个字母的TLD。关于“信息”以及超过3封信件的许多新TLD如何? – rmaddy

+0

谢谢,它正在工作,但作为@rmaddy说,超过3封信,它不会工作? – Rox

+0

@Rox固定为4个字母TLD –

0

在迅速2,

func verifyUrl (str: String?) -> Bool { 
    //Check for nil 
    var urlString = str! 
    if urlString.hasPrefix("http://") || urlString.hasPrefix("https://"){ 

    }else{ 
     urlString = "http://" + urlString 
    } 
    let userURL:String = urlString 

    let regex = try? NSRegularExpression(pattern: "((https|http)://)((\\w|-|m)+)(([.]|[/])((\\w|-)+))+", options: .CaseInsensitive) 
    return regex?.firstMatchInString(userURL, options: [], range: NSMakeRange(0, userURL.characters.count)) != nil 
    }