在 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/