简体   繁体   中英

NSFileManager to search image file in folder

I am using NSFileManager to search "index.png" file. if file doesnt exist then I am trying to display default image. I am using the code below but Its not working. Am i doing something incorrect here?

NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:literature.localURL.path];
path = [path1 stringByAppendingPathComponent:@"index.PNG"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
        cell.preview = [UIImage imageWithContentsOfFile:path1];
    }
    else {
        cell.preview = [UIImage imageNamed:@"Default-HTML5.PNG"];
    }
}

You are setting path equal to two different things. Use a different string for one of them, for example

NSString *path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:literature.localURL.path];

and keep the other the same

and make "index.PNG" "index.png". iOS is case-sensitive.

cell.preview = [UIImage imageWithContentsOfFile: path];

quote apple document :

imageNamed:
Returns the image object associated with the specified filename.

+ (UIImage *)imageNamed:(NSString *)name
Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

your png not in main bundle but in the your folder

imageWithContentsOfFile:
Creates and returns an image object by loading the image data from the file at the specified path.
imageNamed: 

for images

the method looks for an image with the specified name in the application's main bundle.

, for documents dir, you must use

[UIImage imageWithContentsOfFile: path];

as Guo Luchuan said

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM