iphone - 如何在 iphone 应用程序中检查 url 是否有效,然后在 WebVIew 中加载,否则显示警报

标签 iphone ios url uitextfield

我有一个应用程序,我希望当用户在文本字段中输入网址并按返回键时,它应该检查网址是否有效,然后在 WebView 中加载网址,否则显示警报输入有效网址

在我的代码中,它始终显示有效 URL。

 - (BOOL)textFieldShouldReturn:(UITextField *)textField
  {
   [textField setUserInteractionEnabled:YES];
   [textField resignFirstResponder];

test=textField.text;

NSLog(@"Test is working and test is %@",test);

[self  urlIsValiad:test];

if ([test isEqualToString:@"Valid"]) {
    NSURL *url = [NSURL URLWithString:test]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [webView setScalesPageToFit:YES];         
    [self.webView loadRequest:request]; 
}
 else{

  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please enter Valid URL" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
  return YES;
}
- (BOOL) urlIsValiad: (NSString *) url 
{
NSString *regex = 
@"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this 
///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,@?^=%&:/~+#]* [\w-\@?^=%&/~+#])?";
  NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

  if ([regextest evaluateWithObject: url] == YES) {
    NSLog(@"URL is valid!");

    test=@"Valid";

  }  else {
    NSLog(@"URL is not valid!");

   test=@"Not Valid";
}

return [regextest evaluateWithObject:url];
  }

最佳答案

// .h File 
-(BOOL)validateUrl;
.m File
-(BOOL)validateUrl{
    NSString *urlRegEx =  @"((?:http|https)://)?(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
    if ([urlTest evaluateWithObject: self] == YES) {
        NSLog(@"URL is valid!");
    } else {
        NSLog(@"URL is not valid!");
    }
    return [urlTest evaluateWithObject:self];
}
// Main View Controller .m File
if (![txtWebsite.text validateUrl])
    {
        [KWebsiteURLTypeValidation showAsAlert:self];
        return;
    }

关于iphone - 如何在 iphone 应用程序中检查 url 是否有效,然后在 WebVIew 中加载,否则显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18634357/

相关文章:

swift - 如何呈现类似于 MFMailComposeViewController 的 UIViewController

iphone - UIDocumentInteractionController dismissPreviewAnimated 崩溃

ios - 在 iPhone X 中叠加时 UIView 的顶部位置不佳

ios - 如何运行导致框架运行时错误的 iOS 应用程序 "code signature invalid"

c# - 如何在 ASP.NET MVC 3 项目的服务层生成 URL

iphone - 如何从我的应用程序将图像发送到 WhatsApp?

objective-c - 当前位置权限对话框消失得太快

java - 如何在 java 中将文件(通过 URL 寻址)读入字符串?

javascript - 在 asp.net mvc 应用程序中使用 href 属性进行重定向不起作用

iphone - UITapGestureRecognizer 莫名其妙地停止识别点击手势