3

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

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

4

2 回答 2

3

1.你的包中的文件

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.文件在你的目录

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.网络文件

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");
}
于 2015-04-30T08:51:58.387 回答
3

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

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

另请参阅检查 NSURL 是否返回 404

于 2010-01-07T16:06:07.270 回答