且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果url存在Objective-c

更新时间:2022-12-10 12:44:36

创建一个 NSURLConnection 获取url。将 NSURLRequest HTTPMethod 替换为HEADGET。在委托方法 connection:didReceiveResponse:检查 NSHTTPURLResponse $ c的 statusCode $ c> 200或其他成功回应。

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

[请求setHTTPMethod:@HEAD];

NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];
//连接自动启动
}

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

您可以将其他状态代码视为成功,例如



HTTP协议的一部分是设置请求方法。 GET和POST是最常见的两个,但还有其他几个包括HEAD。 HEAD说发送GET发送的相同响应,但不要发送正文。在你的情况下,身体是图像数据。因此,如果HEAD成功,您可以假设GET也将以相同的方式成功,至少在查找静态资源的情况下。


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

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.