If url exists Objective-c

☆樱花仙子☆ 提交于 2019-12-20 10:20:53

问题


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


回答1:


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.




回答2:


connectionWithRequest is depreciated. So you have to use dataTaskWithRequest:

    -(void) queryResponseForURL:(NSURL *)inURL {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:inurl
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:60.0];

        [request setHTTPMethod:@"HEAD"];
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSUInteger respCode=[(NSHTTPURLResponse  *)response statusCode];
            if ( !error&&respCode == 200 ) {
                    // url exists
            } else {
                    // url does not exist
            }

        }];
        [postDataTask resume];
    }


来源:https://stackoverflow.com/questions/2985229/if-url-exists-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!