Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSURL returns 404

Tags:

I need to check whether a URL (represented by a NSURL) is available or returns 404. What is the best way to achieve that?

I would prefer a way to check this without a delegate, if possible. I need to block the program execution until I know if the URL is reachable or not.

like image 625
Erik Avatar asked Sep 10 '09 09:09

Erik


People also ask

How do I know if a website has a return 404?

If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .

How to check 404 in PHP?

Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library.


2 Answers

As you may know already that general error can capture by didFailWithError method:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {     NSLog(@"Connection failed! Error - %@ %@",           [error localizedDescription],           [[error userInfo] objectForKey:NSErrorFailingURLStringKey]); } 

but for 404 "Not Found" or 500 "Internal Server Error" should able to capture inside didReceiveResponse method:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {     if ([response respondsToSelector:@selector(statusCode)])     {         int statusCode = [((NSHTTPURLResponse *)response) statusCode];         if (statusCode == 404)         {             [connection cancel];  // stop connecting; no more delegate messages             NSLog(@"didReceiveResponse statusCode with %i", statusCode);         }     } } 
like image 104
Jirapong Avatar answered Dec 03 '22 15:12

Jirapong


I needed a solution that didn't use a delegate either, so I took pieces of code shown in other answers here and created a simple method that works well in my case (and might be what you are looking for as well):

    -(BOOL) webFileExists {          NSString *url = @"http://www.apple.com/somefile.html";          NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];         NSHTTPURLResponse* response = nil;         NSError* error = nil;         [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];         NSLog(@"statusCode = %d", [response statusCode]);          if ([response statusCode] == 404)             return NO;         else             return YES;      } 
like image 30
woodmantech Avatar answered Dec 03 '22 14:12

woodmantech