If url exists Objective-c

Hey, I have a program that needs to determine if an online image exists, but the only way I got this is to load the image into the NSData pointer and check 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 worked for me, but my problem is that I have a very slow connection and it always takes an image to download. So my question is: is there a way to check if the image (say, http://couleeapps.hostei.com/BottomBox.png ") is available without having to load it in a boolean reporter method?

Help is much appreciated

Higuy

+4
source share
2 answers

Create an NSURLConnection to get the URL. Set HTTPMethod from NSURLRequest to "HEAD" instead of "GET" . In the delegate method connection:didReceiveResponse: check statusCode NSHTTPURLResponse for 200 or another 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 may be other status codes that you would consider success, for example 301.

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

+16
source

connectionWithRequest is amortized. Therefore, you should 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]; } 
+1
source

Source: https://habr.com/ru/post/1312014/


All Articles