Quicker way to save images to documents directory in iOS

551 Views Asked by At

I am trying to save images to my apps documents directory. While I am easily able to save the images to the directory, its taking about two seconds to save an image and its thumbnail. I am using the following methods to save the images using a queue.

+ (void)saveImage:(UIImage*)imageToSave withName:(NSString*)imageName toFolder:(NSString*)folderName
{
    [Utils createFolderWithPath:folderName];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.png",folderName,imageName]];
    NSData *imageData = UIImagePNGRepresentation(imageToSave);
    [imageData writeToFile:savedImagePath atomically:NO];
}
+ (void)createFolderWithPath:(NSString *)folderPath
{
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:folderPath];

    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:&error];
    }
}

is there a faster way? Since I have to save multiple images and 2 seconds per image is a lot of time!

1

There are 1 best solutions below

0
On

You dont need to find the document directory every time. Just find out it one time and store it. and run your code in a thread, thread will save the image in background.