2015-08-08 223 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 
    }