tags:

views:

962

answers:

4

Hi,

I need to check whether a URL, represented by a NSURL is available or returns 404.

What is the best way to achieve that?

Thanks!

heinrich

+2  A: 

As you may know already that general error can capture by 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 by

- (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(@"Error with %@", statusCode);
     }
    }
}
Jirapong
A: 

Is there a way to check this without a delegate? I need to block the program execution until I know if the URL is reachable or not.

Heinrich
+2  A: 

You can achieve a synchronous connection by calling:

NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Your thread will block until the request has beeen made.

Heinrich
+2  A: 

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;
     }
woodmantech