0

ユーザーがテキストフィールドにURLを入力してリターンキーを押すと、URLが有効かどうかを確認し、WebビューにURLをロードする必要があるアプリが必要です

私のコードでは、常に有効な 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];
  }
4

3 に答える 3

1
// .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;
    }
于 2018-01-03T05:45:37.103 に答える
0

この方法を使用できます:

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

URL の有効性を確認するから。お役に立てれば。

于 2013-09-05T10:54:58.913 に答える