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

标签 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 文件等的 bool 值是或否,这样我就可以填写正确的名称来下载用户图片。

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

感谢您的任何建议。

最佳答案

**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,@"");
         }

     }];
}

关于IOS:检查远程文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33255093/

相关文章:

ios - 如何从 SFSafariViewController 获取 URL?

linux - 使用安装在远程服务器系统上的 OpenCV - ubuntu

iOS:UITableView cell.tag 数在进出 View 时不断增加

iphone - iOS - 返回匹配命名方案的文件数

javascript - 如何将 .jpeg url 中的图像访问到 Base64 编码的 javascript

php - 使用 .htaccess 隐藏 URL 关键参数

web-services - IE10中查询字符串参数的编码

mysql - 使 MySQL 可以远程访问,安装在 Windows PC 上

c++ - 带有附加配置的 NetBeans 远程开发

ios - 使用 glReadPixels 读取 Tap Point 的值? OpenGL 2.0 iOS