Question

Trying to select image using photo picker and save that image internally in apps folder.

- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info {

NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;

// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
    == kCFCompareEqualTo) {

    editedImage = (UIImage *) [info objectForKey:
                               UIImagePickerControllerEditedImage];
    originalImage = (UIImage *) [info objectForKey:
                                 UIImagePickerControllerOriginalImage];

    if (editedImage) {
        imageToUse = editedImage;
    } else {
        imageToUse = originalImage;
    }
    // Do something with imageToUse

    //save it
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]];
    NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"];

    NSData *webData = UIImagePNGRepresentation(editedImage);
    NSError* error = nil;
    bool success = [webData writeToFile:imagePath options:NULL error:&error];
    if (success) {
        // successfull save
        imageCount++;
        [[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:@"imageCount"];
        NSLog(@"@Success save to: %@", imagePath);
    }
    else if (error) {
        NSLog(@"Error:%@", error.localizedDescription);
    }
}
...
}

What I can't figure out is that writeToFile::: returns false but no value is returned in error so I can't figure out whats going wrong. Any help would be greatly appreciated thanks

Was it helpful?

Solution

You're missing a "/". The line:

NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]];

should be:

NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", myUniqueID]];

And the line that says:

NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"];

should be:

NSString *imagePath = [imageName stringByAppendingPathExtension:@"png"];

Update:

And, shouldn't:

NSData *webData = UIImagePNGRepresentation(editedImage);

be the following?

NSData *webData = UIImagePNGRepresentation(imageToUse);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top