2

I want to find that whether the URL im giving is valid or not, and whether it exists in internet or not..

Is there any way to do that using objective-C?

一二三
  • 21,059
  • 11
  • 65
  • 74
Raju
  • 441
  • 1
  • 6
  • 17
  • http://regexlib.com/Search.aspx?k=wwww.googls%40e.c%23om&c=1&m=5&ps=10 – iPatel Feb 28 '13 at 05:41
  • 1) http://stackoverflow.com/questions/3791067/check-url-validity 2) http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone – βhargavḯ Feb 28 '13 at 05:42
  • 1
    The selected "duplicate" only answers half of the question. It is not a valid duplicate. This should be reopened. – rmaddy Feb 28 '13 at 18:50
  • I second Maddy... the duplicate is not at all an answer of the question: does the URL return an existing endpoint? – Morkrom Sep 18 '13 at 05:49

1 Answers1

2

You can see if a URL is valid or not by doing the following:

NSString *urlString = ... // some URL to check
NSURL *url = [NSURL URLWithString:urlString];
if (url) {
    // valid URL (meaning it is the proper format)
}

To see if the URL exists in the Internet, you need to perform a HEAD request and check the result. This is more efficient than loading all of the data for the URL.

NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];
[request setHTTPMethod:@"HEAD"];

NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([(NSHTTPURLResponse *)response statusCode] == 200) {
        // url exists
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • So when you call the connection method, what is the response parameter supposed to be? – Morkrom Sep 18 '13 at 07:51
  • You don't call the `connection:didReceiveResponse:` method. It is a delegate method that it called by the framework when a response is received. See the reference documentation. – rmaddy Sep 18 '13 at 15:16
  • 2
    Well. I tested with `http://X X is a non english character ` and it still pass `[NSURL URLWithString:urlString]`. I think we still need to test with regex like [this](http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone). – Yeung Nov 14 '13 at 03:08