首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查某个文件是否存在于特定的URL?

如何检查某个文件是否存在于特定的URL?
EN

Stack Overflow用户
提问于 2010-01-07 23:31:18
回答 2查看 8.6K关注 0票数 3

如何检查网站上是否存在文件?我将NSURLConnectionNSURLRequest一起使用,并使用一个NSMutableData对象来存储didReceiveData:委托方法中返回的内容。然后,在connectionDidFinishingLoading:方法中,我将NSMutableData对象保存到文件系统。一切都很好。例外:如果该文件在网站上不存在,我的代码仍然会运行,获取数据并保存文件。

在我提出下载请求之前,我如何检查文件是否存在?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-01-08 00:06:07

实现connection:didReceiveResponse:,它将在connection:didReceiveData:之前调用。

响应应该是一个NSHTTPURLResponse对象-假设您正在发出一个HTTP请求。因此,您可以检查[response statusCode] == 404以确定该文件是否存在。

另请参见Check if NSURL returns 404

票数 3
EN

Stack Overflow用户

发布于 2015-04-30 16:51:58

1.包中的文件

代码语言:javascript
运行
复制
NSString *path = [[NSBundle mainBundle] pathForResource:@"image"    ofType:@"png"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (fileExists) {
NSLog(@"file exists");
}
else
{
NSLog(@"file not exists");
}

2.目录中的文件

代码语言:javascript
运行
复制
NSString* path =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingPathComponent:@"image.png"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (fileExists) {
NSLog(@"file exists");
}
else
{
NSLog(@"file not exists");
} 

3. web中的文件

代码语言:javascript
运行
复制
NSString *urlString=@"http://eraser2.heidi.ie/wp-content/plugins/all-in-one-seo-pack-pro/images/default-user-image.png";
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@",response);
[connection cancel];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = (int)[httpResponse statusCode];
if (code == 200) {
    NSLog(@"File exists");
}
else if(code == 404)
{
    NSLog(@"File not exist");
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"File not exist");
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2021391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档