如何验证iPhone应用程序中的URL

Que*_*ons 0 iphone url uitextfield ios

如何检查iphone应用程序,如果URL有效,那么它应该打开它,否则它可能会显示它是无效的URL.我正在使用以下代码,但问题是,如果我输入www.google.com它显示有效,如果我输入nice.com也显示有效.

       - (BOOL)textFieldShouldReturn:(UITextField *)textField
      {

       [textField setUserInteractionEnabled:YES];
       [textField resignFirstResponder];
       test=textField.text;

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

   if ([self  urlIsValiad:test]) {
    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];
 }
Run Code Online (Sandbox Code Playgroud)

Mru*_*nal 6

有一个内置函数,命名canOpenURLUIApplication类中.

如果iOS safari可以打开该URL,则返回true/false.

BOOL canOpenGivenURL = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:resultText]];

if (canOpenGivenURL) {

    // URL is valid, open URL in default safari browser
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultText]];

    // write your code here
}
else
    // Not valid URL -- show some alert 
Run Code Online (Sandbox Code Playgroud)

而不是验证所有可用的URL类型,这将更容易验证.

希望这可以帮助.


iPa*_*tel 5

如果要检查URL是否有效,请使用以下RegEx.

NSString *urlString = [NSString stringWithFormat:@"URL_STRING"];
NSString *urlRegEx =
    @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlPredic = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
BOOL isValidURL = [urlPredic evaluateWithObject:urlString];
Run Code Online (Sandbox Code Playgroud)

并把条件这样的

if(isValidURL)
{
  // your URL is valid;
}
else
{
  // show alert message for invalid URL;
}
Run Code Online (Sandbox Code Playgroud)

您也可以将URL转换为合法网址,例如

NSString *urlString = [NSString stringWithFormat:@"URL_STRING"];
NSURL *youURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请检查 stringByAddingPercentEscapesUsingEncoding: