How to check if a file exists at particular URL?

2019-07-17 23:15发布

问题:

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