开发者

iPhone SDK: Check validity of URLs with NSURL not working?

I'm trying to check if a given URL is valid and i'm doing it like this:

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

Since "URLWithString" is supposed to return "nil" if the URL is malformed I thought this would开发者_如何转开发 work but it doesn't for some reason. Could someone please tell me why? Thanks in advance!


NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"yourstring"]];
bool valid = [NSURLConnection canHandleRequest:req];


check this method works fine for me

- (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];

}

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
    }


I think you may be confused regarding the definition of "malformed". Anything conforming to RFC 2396 is considered valid; in practice, it seems NSURL will also accept [ and ] despite their not being allowed by the RFC.

That means pretty much any string of printable ASCII characters besides space, ", % when not followed by two hex digits, <, >, \, ^, `, {, |, and } will be considered "valid", although it may not be absolute or generally useful. Strings containing multiple # may also be rejected.


There is no good explanation for this, the code you provided looks perfectly fine and should work for the purpose you're explaining.

With malformed URLs, do you mean URLs that lead to a 404-error, or URLs with invalid formatting or characters?

Give an example of a malformed URL that returns yes in this function.


In my experience, the NSURL creation routines usually throw an exception instead of returning nil. However, the real question in this case is what constitutes a malformed URL? Are you checking whether a resource exists, or checking whether the structure of the string conforms to the relevant RFCs?

With regards to the first issue I mentioned, when creating URLs that I don't manually enter myself I usually do this:

@try
{
    NSURL * url = [NSURL URLWithString: theString];
    // use the URL
}
@catch (NSException * e)
{
    NSLog( @"URL creation error? %@ - %@", [e name], [e reason] );
    @throw;  // throw the exception again, to hopefully get your attention
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜