Best way to store the downloaded images in iOS

2020-05-09 17:58发布

问题:

Which is the best way to store the downloaded images? From there I should be able to use them anywhere in my application, and images should not be deleted at any case (like low space). Any help please.

回答1:

As per the standard, App related files(Data) need to be stored in document directory only. Once image get download store that images in document directory and maintain unique name for image identification.

-(NSString *)writeDataAsFile:(NSData *)imageData
{

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * thumbNailFilename = [NSString stringWithFormat:@"%@.png",[self GetUUID]]; // Create unique iD
    NSString * thumbNailAppFile = [documentsDirectory stringByAppendingPathComponent:thumbNailFilename];

    if ([imageData writeToFile:thumbNailAppFile atomically:YES])
    {
        return thumbNailFilename;
    }

    return nil;
}

use this method to store the image(downloaded NSData) in document directory.

Retrieve image from the document directory like this

UIImage *thumbnailHomeImage = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"%@",imageName]];


回答2:

take a look at this image caching library. ive used it quite a few times, its really useful