Rox*_*Rox 2 search objective-c nsurl nspredicate ios
我如何检查NSURL是否有效?1)如果我输入"facebook.com",那么它应该添加" http:// www."
2)如果我输入"www.facebook.com",则应添加"http://"
3)如果我输入"facebook",那么它应该在google上搜索.
我怎么能做到这一点?
我正在按照以下方式进行此操作,但它无法正常工作.第三种情况总是如此.(" 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];
}
Run Code Online (Sandbox Code Playgroud)
www.
如果用户输入,则无需添加facebook.com
.这http://
就够了.无论如何,以下功能可以有或没有吃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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2611 次 |
最近记录: |