我如何檢查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];
}
添加的NSLog這個url.absoluteString,結果 – Walucas
您的邏輯是不正確粘貼。對於URL「facebook」,您最終將其更改爲「http:// www.facebook」,然後對其進行驗證。 – rmaddy
@Walucas nslog = absoluteString = http://www.facebook – Rox