views:

52

answers:

2

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!

A: 

Does this have something to do with rights management?

DMan
What sort of rights management? Does the simulator differ than the device in some sort of permissions related way? Thanks for your response!
Peter Hajas
Well, I'm not an iPhone developer, but I heard the iPhone was pretty restrictive... and your line, 'pretty sure it saves out'- does it? I see you do have an NSLog, but if it didn't, it should return an error.
DMan
A: 

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!

Peter Hajas