Search code examples
iosobjective-cuiimageviewnsfilemanager

Save Image Path to NSDocuments then retrieve it as a UIImage


I have an image picker controller that stores selected images into a directory. I am able to save the path fine but retrieving them causes a crash. I'm not sure if the code to save is wrong or the code to retrieve is wrong. This is the crash error.

*** Terminating app due to uncaught exception 
'NSInvalidArgumentException', reason: '-[__NSCFString size]: unrecognized 
selector sent to instance 0x1c484bc40'

Here's the code to retrieve the files and store in a NSMutableArray. This is where the crash happens. I need the results of the paths to be UIImage files.

- (void)loadCustomDesignGIFEdit:(TSPEventRepository *)record {
    NSError *error = nil;
    NSMutableArray *arrSlidshowImg = @[].mutableCopy;
    NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
    NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@%@",Dir, @"/Images/"];
    NSArray * directoryContents = [[NSFileManager defaultManager]
     contentsOfDirectoryAtPath:path error:&error];
    UIImage *image = [UIImage imageWithContentsOfFile:path];

    for (image in directoryContents) {
        [arrSlidshowImg addObject:image];
    }
    NSLog(@"ARRAY RESULT: %@", arrSlidshowImg);

    fourBySixBackgroundImageViewGIF.image = [arrSlidshowImg objectAtIndex:0];      
}

When I press on the button to call loadCustomDesignGIFEdit the log shows a correct path to the image I selected, but it crashes. I need it to save the path as an image with PNG representation into the NSMutableArray.

Here's the log result:

ARRAY RESULT: (
    "picName_IMG_7293.JPG",
    "picName_IMG_7294.JPG"
)

Solution

  • There is a line that says:

    UIImage *image = [UIImage imageWithContentsOfFile:path]
    

    That doesn't make sense, because path is the path of the folder, not of any particular image.

    But your cryptic error stems from the following line of code:

    fourBySixBackgroundImageViewGIF.image = [arrSlidshowImg objectAtIndex:0];
    

    Unfortunately, arrSlidshowImg is an array of strings, not an array of images. So, when you supplied that as the image of your UIImageView, the error is cryptically telling you that it is trying to retrieve the size the image, but the NSString you supplied has no such method/property.

    You probably meant:

    NSString *filename = arrSlidshowImg[0];
    NSString *imagePath = [path stringAppendingPathComponent:filename];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    fourBySixBackgroundImageViewGIF.image = image;