1

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!

Emil
  • 7,220
  • 17
  • 76
  • 135
Chris
  • 391
  • 2
  • 6
  • 17

5 Answers5

18
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"yourstring"]];
bool valid = [NSURLConnection canHandleRequest:req];
Hiren
  • 12,720
  • 7
  • 52
  • 72
Adam Shiemke
  • 3,734
  • 2
  • 22
  • 23
5

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
    }
Sanjeev sharma
  • 169
  • 1
  • 6
3

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.

Anomie
  • 92,546
  • 13
  • 126
  • 145
0

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.

Emil
  • 7,220
  • 17
  • 76
  • 135
  • What I'm trying to do is to validate a URL entered by the user and usually this is done using a regex. But I noticed a lot of people suggesting just to use "URLWithString" since it's supposed to return nil if the URL is invalid. A URL is invalid as soon something like this is entered as a URL for example: "0000". – Chris Mar 20 '11 at 20:06
0

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
}
Jim Dovey
  • 11,166
  • 2
  • 33
  • 40
  • I've never seen an exception in this case, for which valid (i.e. not a not initialized local variable) NSStrings does that happen? – Matthias Bauch Mar 20 '11 at 19:37
  • If I try to create a URL using [NSURL URLWithString: @"argleblargle"] it throws. Then again, in virtually all my iOS programming I always alloc/init and explicitly release, so maybe it only throws from -initWithString: – Jim Dovey Mar 20 '11 at 19:39
  • Neither `[NSURL URLWithString: @"argleblargle"]` nor `[[NSURL alloc] initWithString: @"argleblargle"]` throws an exception when I try it here. The documentation also explicitly states that `URLWithString:` will return nil. Are you sure something else in your code isn't throwing when passed a nil NSURL? – Anomie Mar 20 '11 at 20:44
  • It's always thrown for me. Maybe it changed in a later iOS version? I've had to wrap all NSURL initialization with try/catch loops since iOS 2.0, and the exceptions generated were NSInvalidArgumentExceptions with reasons mentioning -[NSURL initWithString:]. Perhaps it was just fixed in iOS 4.x. – Jim Dovey Mar 21 '11 at 00:58
  • 1
    There is a note in [Apple's NSURL class reference for URLWithString](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/index.html#//apple_ref/occ/clm/NSURL/URLWithString:) reference stating "In OS X v10.7 and later or iOS 5 and later, this method returns nil if the URL string is nil. In earlier versions, this method throws an exception if the URL string is nil." – user2067021 Mar 03 '16 at 02:00