Save An Image To Application Documents Folder From UIView On IOS

It’s all good, man. Don’t harm yourself or others.

You probably don’t want to store these images in Core Data, since that can impact performance if the data set grows too large. Better to write the images to files.

NSData *pngData = UIImagePNGRepresentation(image);

This pulls out PNG data of the image you’ve captured. From here, you can write it to a file:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

Reading it later works the same way. Build the path like we just did above, then:

NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

What you’ll probably want to do is make a method that creates path strings for you, since you don’t want that code littered everywhere. It might look like this:

- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name]; 
}

Hope that’s helpful.

Leave a Comment