如何检查网站上是否存在文件?我使用NSURLConnection
与我的NSURLRequest
和NSMutableData
对象来存储didReceiveData:
委托方法中返回的内容。在connectionDidFinishingLoading:
方法中,我将NSMutableData
对象保存到文件系统。都好。除了:如果文件不存在于网站上,我的代码仍然运行,获取数据并保存文件。如何检查文件是否存在于特定的URL?
如何在下载请求之前检查文件是否存在?
如何检查网站上是否存在文件?我使用NSURLConnection
与我的NSURLRequest
和NSMutableData
对象来存储didReceiveData:
委托方法中返回的内容。在connectionDidFinishingLoading:
方法中,我将NSMutableData
对象保存到文件系统。都好。除了:如果文件不存在于网站上,我的代码仍然运行,获取数据并保存文件。如何检查文件是否存在于特定的URL?
如何在下载请求之前检查文件是否存在?
执行connection:didReceiveResponse:
,将在connection:didReceiveData:
之前调用。
响应应该是NSHTTPURLResponse
对象 - 假设您正在发出HTTP请求。因此,您可以检查[response statusCode] == 404
以确定文件是否存在。请参阅Check if NSURL returns 404。
非常感谢Kenny。你知道我是否可以/应该在我的didReceiveResponse中实施以下内容? NSHTTPURLResponse * httpResponse =(NSHTTPURLResponse *)response; if([httpResponse statusCode] == 404)//文件不存在 { [连接取消]; } – 2010-01-07 16:53:35
对不起,应该补充说,所有的作品都是一种享受。只是想知道是否建议取消这样的连接? – 2010-01-07 17:06:57
这不起作用。它给出了一个误报 - 当没有文件时,错误地指示文件的存在。 – dugla 2012-02-15 17:45:53
1.FILE组合中的
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.File在网络
NSString *[email protected]"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");
}
这就是为什么存在'HEAD'动词在HTTP中,而不是发出'GET'请求。 – Cyrille 2015-04-30 08:55:49