iPhone SDK:检查NSURL无效的网址的有效性?

Chr*_*ris 1 iphone url sdk objective-c nsurl

我正在尝试检查给定的URL是否有效,我这样做:

- (BOOL)urlIsValid:(NSString *)address {
    NSURL *testURL = [NSURL URLWithString:address];
    if (testURL == nil) {
        return NO;
    }
    else {
        return YES;
    }
}
Run Code Online (Sandbox Code Playgroud)

因为"URLWithString"应该返回"nil",如果URL格式不正确,我认为这会起作用,但它不是出于某种原因.有人可以告诉我为什么吗?提前致谢!

Ada*_*mke 17

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"yourstring"]];
bool valid = [NSURLConnection canHandleRequest:req];
Run Code Online (Sandbox Code Playgroud)


小智 5

检查这个方法对我来说很好

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

}

if (![self validateUrl:strRSSurl]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Invalid url" message:[NSString stringWithFormat:@"\"%@\"",strRSSurl] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show ];
        [alert setTag:7];
    }
    else
    {
      valid url
    }
Run Code Online (Sandbox Code Playgroud)