Reputation: 191
I am getting images from url and saving to file. My codes for saving and loading:
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:@"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
} else {
NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
}
}
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
return result;
}
Downloading images, saving to file and loading from file are successfully working. But I want to get all images that I save to file. So I don't want to specify image name. How can I do this?
Upvotes: 0
Views: 131
Reputation:
When you save the images you have, make some naming convention, i.e. image01.png, image02.png, image03.png so when you'll load them you can simply iterate through a For Loop and call the function you already wrote:
for (int i = 1; i <= imagesCount; i++) {
NSString* twoDigitNumber;
if (i < 10) {
twoDigitNumber = [NSString stringWithFormat:@"0%d", i];
}
else {
twoDigitNumber = [NSString stringWithFormat:@"%d", i];
}
NSString* imageName = [NSString stringWithFormat:@"image%@", twoDigitNumber];
UIImage* image = [self loadImage:imageName inDirectory:......]; // Complete your code here
}
Upvotes: 1
Reputation: 25632
You must know what you want to read. There are probably many approaches - here are two:
store the filenames of each file and iterate over those filenames.
store the images in some directory and loop over the directory contents.
Upvotes: 1