0

Is there any resource efficient way (something that does not tie up the main thread) in IOS to check the existence of a remote file?

I have user images stored on a server. While there is a consistent url scheme, some images are .jpg, others are .gif, etc. so to get the correct image name, I need to check does user/file.gif exist, user/file.jpg exist etc. in order to download the file to the IOS app.

I found this code in another answer in IOS

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"HEAD"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

But I am not sure how to use it. Ideally, I would like to get a boolean yes or no as to whether the .gif file exists, the .jpg file exists etc for the users profile pic so I can fill in the correct name to download the user pic.

The alternative would be to write a service on the back end to return the file but wondering if it can all be done in IOS.

Thanks for any suggestions.

Community
  • 1
  • 1
user1904273
  • 4,562
  • 11
  • 45
  • 96

1 Answers1

4
**Use this function below to check whether file exists at specified url**

+(void)checkWhetherFileExistsIn:(NSURL *)fileUrl Completion:(void (^)(BOOL success, NSString *fileSize ))completion
{
    //MAKING A HEAD REQUEST
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl];
    request.HTTPMethod = @"HEAD";
    request.timeoutInterval = 3;

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
         if (connectionError == nil) {
             if ((long)[httpResponse statusCode] == 200)
             {
                 //FILE EXISTS

                 NSDictionary *dic = httpResponse.allHeaderFields;
                 NSLog(@"Response 1 %@",[dic valueForKey:@"Content-Length"]);
                 completion(TRUE,[dic valueForKey:@"Content-Length"]);
             }
             else
             {
                 //FILE DOESNT EXIST
                 NSLog(@"Response 2");
                 completion(FALSE,@"");
             }
         }
         else
         {
             NSLog(@"Response 3");
             completion(FALSE,@"");
         }

     }];
}
user2885077
  • 702
  • 6
  • 14