IOS:检查远程文件是否存在

时间:2015-10-21 09:02:37

标签: ios url remote-server

在IOS中是否有任何资源有效的方法(不会占用主线程)来检查远程文件是否存在?

我将用户图像存储在服务器上。虽然有一致的url方案,但有些图像是.jpg,其他图像是.gif等。所以为了获得正确的图像名称,我需要检查是否存在user / file.gif,user / file.jpg存在等等。为了将文件下载到IOS应用程序。

我在另一个answer in IOS

中找到了此代码
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"HEAD"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

但我不确定如何使用它。理想情况下,我想得到一个布尔值是或否是关于.gif文件是否存在,.jpg文件是否存在等用户个人资料图片所以我可以填写正确的名称来下载用户图片。

另一种方法是在后端编写服务以返回文件,但想知道是否可以在IOS中完成所有操作。

感谢您的任何建议。

1 个答案:

答案 0 :(得分: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,@"");
         }

     }];
}