views:

276

answers:

1

Hey, I have a program that needs to tell if an online image exists, but the only way that I've gotten this to work is by loading the image in a NSData pointer and checking if the pointer exists.

- (BOOL)exists {
      NSString *filePath = @"http://couleeapps.hostei.com/BottomBox.png";
      NSURL *url = [NSURL URLWithString:filePath];
      NSData *imageData = [NSData dataWithContentsOfURL:url];
      if (imageData) {
            return YES;
      }
            return NO;
}

This has worked for me, but my problem is that I have a very slow connection, and it takes forever to download the image. So my question is: is there a way to put checking if a image (say "http://couleeapps.hostei.com/BottomBox.png") is available without having to download it in a Boolean reporter method?

Help is much appreciated

HiGuy

+3  A: 

Create an NSURLConnection to fetch the url. Set the HTTPMethod of the NSURLRequest to "HEAD" instead of "GET". In the delegate method connection:didReceiveResponse: check the statusCode of the NSHTTPURLResponse for 200 or other success response.

-(void) queryResponseForURL:(NSURL *)inURL {
  NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];

  [request setHTTPMethod:@"HEAD"];

  NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];
  // connection starts automatically
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  if ( [(NSHTTPURLResponse  *)response statusCode] == 200 ) {
    // url exists
  }
}

There could be other status codes that you would treat as success, like 301.

Part of the HTTP protocol is setting the request method. GET and POST are the two most common, but there are several others including HEAD. HEAD says send the same response you would send for GET, but do not send the body. In your case the body is the image data. So if HEAD succeeds, you can assume that GET would also succeed in the same way, at least in the case of looking up a static resource.

drawnonward
Could you explain this a little more? I am finding it hard to understand.
HiGuy Smith
HEAD: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
JeremyP
This is great, but how would I call this function in a boolean reporter method multiple times? I'm trying to use a "done" variable to check, but it is not working. Can you add a working -(bool)queryResponseForURL: method?
HiGuy Smith