Never_be
Never_be

Reputation: 849

Cannot load image to UIImageView from absolute path

I use UIImagePickerController to pick image and load to my UIImageView, but I want to save user pick and load it later, I think will be good save absolute path to user defaults but not working (

How I save path // all working

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:   (NSDictionary *)info
{

[self.backgroundImage setImage:info[UIImagePickerControllerOriginalImage]];
NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];

//in localUrl I see: assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG

NSUserDefaults *saves = [NSUserDefaults standardUserDefaults];
[saves setValue:[localUrl absoluteString] forKey:@"backimage"];
[saves synchronize];

[self dismissViewControllerAnimated:YES completion:nil];
}

How I try to load: //not working (

NSUserDefaults *saves = [NSUserDefaults standardUserDefaults];

if(![saves objectForKey:@"backimage"]){

 [self.backgroundImage setImage:[UIImage imageNamed:@"gameBackiPhone"]];

}else{

 NSURL *url = [NSURL URLWithString:[saves objectForKey:@"backimage"]];

//in url I see: assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG

 UIImage *bimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];

 [self.backgroundImage setImage:bimage];

}

How must be I cannot find.

Upvotes: 0

Views: 450

Answers (1)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

You can not load image directly using Asset URL, you need to use ALAssetsLibrary class to achieve it. Use following snippet to load image using Asset URL.

// *** It will return Asset from URL passed, create Image from Asset and set into your `UIImageView` ***
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        UIImage *largeimage = [UIImage imageWithCGImage:iref];
        yourImageView.image = largeImage;
    }
};

// *** If any error occurs while getting image from Asset Library following block will be invoked ***
ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
{
    NSLog(@"Can't get image - %@",[myerror localizedDescription]);
};

// *** Set Asset URL to load Image (assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG) ***
[NSURL *asseturl = [NSURL URLWithString:yourURL];
// *** Create ALAssetsLibrary Instance and load Image ***
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
            resultBlock:resultblock
           failureBlock:failureblock];

Dont forget to import AssetsLibrary framework in your project.

Upvotes: 1

Related Questions