Search code examples
iphoneobjective-ciosuiimageviewnsdocumentdirectory

objective-c: failed to write image to documents directory


I'm using this piece of code to try and save an image to the documents directory:

//FOR TESTING ON SIMULATOR 
UIImage* image = [UIImage imageNamed:@"ReceiptImage1.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString* imageName = @"Receipt1Image1.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];        
[imageData writeToFile:fullPathToFile atomically:NO];

self.receiptImage1 = fullPathToFile;

self.receiptImageView1.image = [UIImage imageWithContentsOfFile:fullPathToFile];

NSLog(@"fullPathToFile %@", fullPathToFile);

However this piece of code doesn't set the imageViews image to the receipt image that I'm trying to write to the documents directory.

Can someone explain what I'm doing wrong and how to fix it?

Thanks,

Jack


Solution

  • Use this:

    - (void)saveImage:(UIImage*)image:(NSString*)imageName{
    NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
    
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path 
    
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
    
    NSLog(@"image saved");}