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.
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 .
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.
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); } } }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With