如何检查网站上是否存在文件?我正在使用NSURLConnection
和NSURLRequest
以及NSMutableData
对象来存储didReceiveData:
委托方法中返回的内容。在connectionDidFinishingLoading:
方法中,我将NSMutableData
对象保存到文件系统。都好。除外:如果网站上不存在该文件,我的代码仍会运行,获取数据并保存文件。
在下载请求之前,如何检查文件是否存在?
答案 0 :(得分:3)
实施connection:didReceiveResponse:
,将在connection:didReceiveData:
之前调用。
响应应该是NSHTTPURLResponse
对象 - 假设您正在发出HTTP请求。因此,您可以检查[response statusCode] == 404
以确定文件是否存在。
答案 1 :(得分:2)
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.File在您的目录中
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 in web
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");
}