How to check if a file exists in Documents folder?
I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.
Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.
How I can do that? With NSFileManager
I can't get outside of main开发者_如何学编程Bundle
..
Swift 3:
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
Objective-C:
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.
NSFileManager Class Reference
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.
Source: Apple Developer API Reference
From the secure coding guide.
To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
Swift 2.0
This is how to check if the file exists using Swift
func isFileExistsInDirectory() -> Bool {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")
return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);
//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
NSLog("File not exist");
} else {
NSLog("File exist");
}
//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
cell.photoImageView.image = image;//Display image
}
NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error
to do so
NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
NSLog(@"%@ exists", fileURL);
} else {
NSLog(@"%@ existence checking error: %@", fileURL, error);
}
Or using Swift
if let url = URL(fileURLWithPath: NSHomeDirectory()) {
do {
let result = try url.checkResourceIsReachable()
} catch {
print(error)
}
}
精彩评论