Testing file existence using NSURL
Solution 1:
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];
Solution 2:
On iOS I couldn't find any other way...
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"file.type"];
if ([[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {...}
Solution 3:
Here is the Swift 2 answer:
var error:NSError?
let folderExists = theURL.checkResourceIsReachableAndReturnError(&error)
Solution 4:
Determining if a given file (or file-reference) URL refers to a file-system object that exists is inherently costly for remote resources, the 10.6 only (no iPhoneOS) api's for this CFURLResourceIsReachable() and [NSURL checkResourceIsReachableAndReturnError:] are both synchronous, even if you would be using them, for a lot of files you would still be looking at a significant delay overhead.
What you should do is implement your own asynchronous checking routine with caching that separately creates a list of valid resources.
Otherwise the notes for CFURLResourceIsReachable in the header state :
An example would be periodic maintenance of UI state that depends on the existence of a particular document. When performing an operation such as opening a file, it is more efficient to simply try the operation and handle failures than to check first for reachability.