如何检查网站上是否存在文件?我将NSURLConnection
与NSURLRequest
一起使用,并使用一个NSMutableData
对象来存储didReceiveData:
委托方法中返回的内容。然后,在connectionDidFinishingLoading:
方法中,我将NSMutableData
对象保存到文件系统。一切都很好。例外:如果该文件在网站上不存在,我的代码仍然会运行,获取数据并保存文件。
在我提出下载请求之前,我如何检查文件是否存在?
发布于 2010-01-07 16:06:07
实现connection:didReceiveResponse:
,它将在connection:didReceiveData:
之前调用。
响应应该是一个NSHTTPURLResponse
对象-假设您正在发出一个HTTP请求。因此,您可以检查[response statusCode] == 404
以确定该文件是否存在。
发布于 2015-04-30 08:51:58
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. 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");
}
https://stackoverflow.com/questions/2021391
复制