IOS checks whether the file in the specified path exists.
This article will share with you how to check whether a specified file exists in IOS development. Four methods are provided for you, which are very practical. You can choose your preferred method based on your needs.
The Code is as follows:
-(NSString *) dataPath :( NSString *) file
{
NSString * path = [[NSHomeDirectory () stringByAppendingPathComponent: @ "events"] stringByAppendingPathComponent: @ "badge"];
BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath: path withIntermediateDirectories: YES attributes: nil error: nil];
NSAssert (bo, @ "failed to create directory ");
NSString * result = [path stringByAppendingPathComponent: file];
Return result;
}
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Specify the image access path (written to the application sandbox by default)
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
// Give the file a file name
NSString * imageDir = [[[paths objectAtIndex: 0] stringByAppendingPathComponent: @ "163"] stringByAppendingPathComponent: @ "songzi"];
// Folder for storing images
NSString * imagePath = [imageDir stringByAppendingPathComponent: @ "file name .png"];
NSData * data = nil;
// Check whether the image is saved locally
If ([self isExistsFile: imagePath]) {
Data = [NSData dataWithContentsOfFile: imagePath];
} Else {
Data = [NSData dataWithContentsOfURL: [NSURL URLWithString: @ ""];
// Create a folder path
[[NSFileManager defaultManager] createDirectoryAtPath: imageDir withIntermediateDirectories: YES attributes: nil error: nil];
// Create an image
[UIImagePNGRepresentation ([UIImage imageWithData: data]) writeToFile: imagePath atomically: YES];
}
ImageView. image = [UIImage imageWithData: data];
}
Check whether the file exists
The Code is as follows:
NSString * path = [[NSBundle mainBundle] pathForResource: fileName ofType: @ ""];
If (path = NULL)
Method 2:
The Code is as follows:
NSFileManager * fileManager = [NSFileManager defaultManager];
// Get documents directory
NSArray * directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectoryPath = [directoryPaths objectAtIndex: 0];
If ([fileManager fileExistsAtPath: @ ""] = YES ){
NSLog (@ "File exists ");
}
Method 3:
The Code is as follows:
// Determine whether a file exists
If (! [C judgeFileExist: @ "user. plist"])
{
NSLog (@ "check whether the file exists! ");
Return;
}
Method 4:
The Code is as follows:
// Determine whether a file exists
-(BOOL) judgeFileExist :( NSString *) fileName
{
// Obtain the file path
NSString * path = [[NSBundle mainBundle] pathForResource: fileName ofType: @ ""];
If (path = NULL)
Return NO;
ReturnYES;
}