【问题标题】:Validate NSString as URL with proper scheme host and domain使用适当的方案主机和域将 NSString 验证为 URL
【发布时间】:2014-02-03 10:48:48
【问题描述】:

我正在尝试将字符串验证为正确的URL's,它可以符合以下格式之一

  • www.site.domain...(任何合法的结构)
  • http(s)://site.domain...(任何合法的结构)
  • http(s)://site.domain...(任何合法的结构)

问题是它正在验证文本

http://cat

这显然很糟糕。

我的代码是:

BOOL isReachable = [self validateIsReachable:text];
    if (!isReachable)
    {
        if ([text hasPrefix:@"http://"] || [text hasPrefix:@"https://"])
        {
            BOOL valid = [NSString validateUrlString:text];
            if (!valid)
            {
                                // need to do something...
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bad url" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                return;
            }

        } else {
            text = [NSString stringWithFormat:@"http://%@",text];
            isReachable = [self validateIsReachable:text];
            if (!isReachable)
            {
                                // need to do something
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bad url" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                return;
            }
        }
    }

    NSURLRequest *request = [self requestForString:text];
    [self.webView loadRequest:request];
}

-(BOOL)validateIsReachable:(NSString *)text
{
    return [NSString isValidUrl:text];



+(BOOL)isValidUrl:(NSString *)candidate
{
    NSURL *candidateURL = [NSURL URLWithString:candidate];
    // WARNING > "test" is an URL according to RFCs, being just a path
    // so you still should check scheme and all other NSURL attributes you need
    NSString *scheme = candidateURL.scheme;
    NSString *host = candidateURL.host;
    BOOL v = [NSString validateUrlString:candidate];
    if (candidateURL && candidateURL.scheme && candidateURL.host) {
        // candidate is a well-formed url with:
        //  - a scheme (like http://)
        //  - a host (like stackoverflow.com)
        return YES;
    }
    return NO;
}

+(BOOL)validateUrlString:(NSString*)urlString
{
    if (!urlString)
    {
        return NO;
    }

    NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];

    NSRange urlStringRange = NSMakeRange(0, [urlString length]);
    NSMatchingOptions matchingOptions = 0;

    if (1 != [linkDetector numberOfMatchesInString:urlString options:matchingOptions range:urlStringRange])
    {
        return NO;
    }

    NSTextCheckingResult *checkingResult = [linkDetector firstMatchInString:urlString options:matchingOptions range:urlStringRange];

    return checkingResult.resultType == NSTextCheckingTypeLink
    && NSEqualRanges(checkingResult.range, urlStringRange);
}

加载网页时 - UIWebview 委托调用

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
// NSURLErrorDomain - A server with the specified hostname could not be found
    if (error.code == -1003)
    {
      // bad domain or unreachable (valid url structure but host isn't around)
    }
}

如果主机无法访问,我想获取主机名并对其执行 google 搜索

例如在验证的情况下

http://cat

我要提取cat

但是如果是的话

http://<www>cat.com(or any proper domain) 

我想显示主机实际上无法访问的错误

【问题讨论】:

  • 为什么验证 URL 如此重要?为什么不尝试访问由 URL 定义的资源,您会很快知道它是否有效。
  • 因为如果你输入 nsurlrequest 会失败:www.cat.com 因为之前没有“http://”
  • 那你就知道它是无效的。这不是“完成工作”吗?

标签: ios objective-c validation url uiwebview


【解决方案1】:

尝试使用 NSUrl 的host:

  NSURL *URL = [NSURL URLWithString:url];
  NSLog(@"%@", [URL host]);

使用它,您将获得可以在错误中显示的受人尊敬的主机名。请同时阅读文档。

希望对你有帮助!

【讨论】:

    【解决方案2】:

    试试这个检查验证

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

    参考link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2017-12-04
      • 2011-07-28
      • 1970-01-01
      • 2014-08-27
      • 2020-10-15
      相关资源
      最近更新 更多