How to check if a file exists at particular URL?

橙三吉。 提交于 2019-12-12 19:06:54

问题


How do I check if a file exists on a web site? I am using NSURLConnection with my NSURLRequest and an NSMutableData object to store what comes back in the didReceiveData: delegate method. In the connectionDidFinishingLoading: method I then save the NSMutableData object to the file system. All good. Except: if the file does not exist at the website, my code still runs, gets data and saves a file.

How can I check the file is there before I make download request?


回答1:


Implement connection:didReceiveResponse:, which will be called before connection:didReceiveData:.

The response should be an NSHTTPURLResponse object — suppose you're issuing an HTTP request. You can therefore check [response statusCode] == 404 to determine if the file exists or not.

See also Check if NSURL returns 404.




回答2:


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.File in your directory

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");
}


来源:https://stackoverflow.com/questions/2021391/how-to-check-if-a-file-exists-at-particular-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!