Question

I use NSData to persist an image in my application. I save the image like so (in my App Delegate):

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"Saving data");

    NSData *data = UIImagePNGRepresentation([[viewController.myViewController myImage]image]);
    //Write the file out!

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];

    [data writeToFile:path_to_file atomically:YES];
    NSLog(@"Data saved.");
}

and then I load it back like so (in my view controller, under viewDidLoad):

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];

if([[NSFileManager defaultManager] fileExistsAtPath:path_to_file])
{
    NSLog(@"Found saved file, loading in image");
    NSData *data = [NSData dataWithContentsOfFile:path_to_file];

    UIImage *temp = [[UIImage alloc] initWithData:data];
    myViewController.myImage.image = temp;
    NSLog(@"Finished loading in image");
}

This code works every time on the simulator, but on the device, it can never seem to load back in the image. I'm pretty sure that it saves out, but I have no view of the filesystem.

Am I doing something weird? Does the simulator have a different way to access its directories than the device?

Thanks!

Was it helpful?

Solution

Aha! Nailed it!

I'm writing this so someone else pulling their hair doesn't sit there staring at code, wondering why it doesn't work :)

The problematic line is this one:

NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];

It should look like this:

NSString *path_to_file = [documentsDirectory stringByAppendingPathComponent:@"lastimage.png"];

The reason for this is, without it, you'd get something along the lines of /Files/Documentslastimage.png instead of /Files/Documents/lastimage.png, as the path component appending takes care of the slashes for you. I hope this helps someone else in the future!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top