Bazinga
Bazinga

Reputation: 2466

Saving in NSDocumentDirectory

Having weird problem with my NSDocumenDirectory saving. Here is a sneak preview: First I pick images ( in my imagePickerViewController):

enter image description here

in my PreviewController:

enter image description here

So at first try, it was okay.

Then I revisit the imagePickerViewController to add another image:

enter image description here

in my PreviewController:

enter image description here

This is where the problem occurs. At the image above, it recopies the last image from the old preview (like a duplicate). I dunno what Im doing wrong in my codes. But Im saving it when a file exist. Kindly see:

for (int i = 0; i < info.count; i++) {
    NSLog(@"%@", [info objectAtIndex:i]);
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,    NSUserDomainMask ,YES );
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"firstSlotImages%d.png", i]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {

            NSLog(@"file doesnt exist");

        } else {
            ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
            UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
            //----resize the images
            image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];

            NSData *imageData = UIImagePNGRepresentation(image);
            [imageData writeToFile:savedImagePath atomically:YES];

            NSLog(@"saving at:%@",savedImagePath);
        }
}

What I need is to just reAdd AGAIN the same image with the new one. Same as, like the last preview.

Upvotes: 2

Views: 818

Answers (1)

Jesse Gumpo
Jesse Gumpo

Reputation: 4787

The four images are passed in the sequence that they show in the preview, so in the first example the orange cat is third, and in the second example, the orange cat is fourth. The new image isn't saving because it is third, and you already have a file named "firstSlotImages2.png". If you re-save each image without checking if the file exists, you should get the result you are looking for.

There's a key in the media info: UIImagePickerControllerMediaURL which returns an NSURL, convert it to a string and get the the lastPathComponent. Use this as the file name to save to the directory you are saving it to. You can then save the reference to these images by saving this same file name either in an NSMutableArray, or an NSMutableDictionary

Upvotes: 1

Related Questions