Unable to load image from asset URL

CodeMilian picture CodeMilian · Jan 24, 2013 · Viewed 18.1k times · Source

I have a class that stores information about the assets on the phone (images, videos).

My class has the ResourceURLString defined as such

@property NSURL *ResourceURL;

I am setting the property while looping trough the assets on the phone as such

Item.ResourceURLString = [[asset valueForProperty:ALAssetPropertyURLs] objectForKey:[[asset valueForProperty:ALAssetPropertyRepresentations] objectAtIndex:0]];

When the user clicks on an image I want to load the image.

The code that I have is this

NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:[CurrentItem.ResourceURL absoluteString]]];    

Img = [UIImage imageWithData:imageUrl];

But the Image is always nil I have verified that the ResourceURL property contains the URL assets: library://asset/asset.JPG?id=82690321-91C1-4650-8348-F3FD93D14613&ext=JPG

Answer

Midhun MP picture Midhun MP · Jan 24, 2013

You can't load images in this way.

You need to use ALAssetsLibrary class for this.

Add assetslibrary framework to your project and add header files.

Use the below code for loading image:

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        UIImage *largeimage = [UIImage imageWithCGImage:iref];
        yourImageView.image = largeImage;
    }
};

ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
{
    NSLog(@"Can't get image - %@",[myerror localizedDescription]);
};

NSURL *asseturl = [NSURL URLWithString:yourURL];
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl 
                   resultBlock:resultblock
                  failureBlock:failureblock];