Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing file existence using NSURL

Snow Leopard introduced many new methods to use NSURL objects to refer to files, not pathnames or Core Services' FSRefs.

However, there's one task I can't find a URL-based method for: Testing whether a file exists. I'm looking for a URL-based version of -[NSFileManager fileExistsAtPath:]. Like that method, it should return YES if the URL describes anything, whether it's a regular file, a directory, or anything else.

I could attempt to look up various resource values, but none of them are explicitly guaranteed to not exist if the file doesn't, and some of them (e.g., NSURLEffectiveIconKey) could be costly if it does.

I could just use NSFileManager's fileExistsAtPath:, but if there's a more modern method, I'd prefer to use that.

Is there a simple method or function in Cocoa, CF, or Core Services that's guaranteed/documented to tell me whether a given file (or file-reference) URL refers to a file-system object that exists?

like image 234
Peter Hosey Avatar asked Dec 18 '09 11:12

Peter Hosey


1 Answers

NSURL does have this method:

- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error 

Which "Returns whether the resource pointed to by a file URL can be reached."

NSURL *theURL = [NSURL fileURLWithPath:@"/Users/elisevanlooij/nonexistingfile.php"                 isDirectory:NO]; NSError *err; if ([theURL checkResourceIsReachableAndReturnError:&err] == NO)     [[NSAlert alertWithError:err] runModal]; 
like image 58
Elise van Looij Avatar answered Oct 05 '22 18:10

Elise van Looij