Retrieve multiple images from document directory

喜你入骨 提交于 2019-12-10 12:19:30

问题


I have folder named "2" in document directory. Now in folder "2", I have five images named 0.png, 1.png, 2.png, 3.png and 4.png. I want to retrieve these images and save into an array. I have code but it returns only one image.

int b=2;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSLog(@"%@",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d/0.png",b]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
NSLog(@"%@",getImagePath);
imge.image=img;

回答1:


Just use NSFileManager, something like this:

[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];

It will give you an array with all the file paths for all files in the given path.


This is how you load the images from the array of URLs.

NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
for (NSURL *url in paths)
{
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}



回答2:


You should loop through the images.

int b=2;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSLog(@"%@",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSMutableArray *images = [NSMutableArray arrayWithCapacity:5];

for (int i = 0; i < 5; i++)
{
   NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString     stringWithFormat:@"%d/%d.png",b, i]];
   UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
   [images addObject:img];
   NSLog(@"%@",getImagePath);
   imge.image=img;
}

Instead of hardcoding the count and names of the image files, as Dominik suggested you should use contentsOfDirectoryAtPath:error: to get the list of files in that directory.

NSError *error = nil;
NSArray *imageFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",b]] error:&error];


来源:https://stackoverflow.com/questions/17747860/retrieve-multiple-images-from-document-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!