sensslen sensslen - 1 year ago 82
iOS Question

How to save and reload image using ALAsset?

I'm writing an app that lets users take Photos and assign them to a Device. For this I need to be able to store the URL of the taken Picture and reload the Picture afterwards.

I know there have been several discussions on that, but strangely none of the Ansers helped me...

So here's my Code for saving an Image:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];
UIImage * image;

// Request to save Image
if ([picker sourceType] == UIImagePickerControllerSourceTypeCamera) {
image = [info objectForKey:UIImagePickerControllerEditedImage];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL * assertURL, NSError * error){
if (error) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"PictureSaveErrorTitle", @"Title if saving picture fails")
message:NSLocalizedString(@"PictureSaveErrorMessage", @"Message if saving picture fails")
cancelButtonTitle:NSLocalizedString(@"PictureSaveErrorOK", @"OK if saving picture fails")
[alert show];
} else {
[self setUserImage:[assertURL absoluteString]];
[imageOfDevice setImage:image];
} else {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self setUserImage:[[info valueForKey:UIImagePickerControllerReferenceURL] path]];

[self dismissModalViewControllerAnimated:YES];

And this is for reloading the Image:

if (userImage != nil) {
ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL fileURLWithPath:userImage]
resultBlock:^(ALAsset * asset){
[imageOfDevice setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
failureBlock:^(NSError * error){
NSLog(@"cannot get image - %@", [error localizedDescription]);

Does anybody see any fault?

Thanks for helping,


Answer Source

The simple solution is that you are passing in the absoluteString to instead of the NSUrl.

This code works for me inside picker did finish.

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset )
            NSLog(@"we have our ALAsset!");
                failureBlock:^(NSError *error )
             NSLog(@"Error loading asset");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download