7
votes

I am trying to develop an application which would download images (from a photography site) and create a ALAsset for each image and then place them under a new ALAssetsGroup.

I am able to create a new Album (ALAssetsGroup) and download data from the website. However i am a bit stuck on how to create the new ALAsset.

I have tried is as follows

            ALAsset *asset = [[[ALAsset alloc] init] autorelease];
            NSDictionary *metadata = [NSDictionary dictionaryWithObjectsAndKeys:p.id, @"id", p.thumbnail_url, @"thumbnail_url", p.photo_url, @"photo_url", nil];
            [asset setImageData:data metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
                ESLog(@"Asset %@ created error:%@", assetURL, error);
                [group addAsset:asset];
            }];

However I get prints where both the assetURL and error is empty.

2012-04-15 02:58:06.850 XXXXXX.com[5966:c607] Asset (null) created error:(null)

It would be great if someone can suggest how i can create a new Asset in an Album

3

3 Answers

6
votes

you cant create a new ALAsset like that. What you need to do is save you image data to the Photo-Library using the method:

- (void)writeImageDataToSavedPhotosAlbum:(NSData *)imageData metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock

The completion block will return the NSURL for the new created asset. Using the method

- (void)assetForURL:(NSURL *)assetURL resultBlock:(ALAssetsLibraryAssetForURLResultBlock)resultBlock failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock

with the NSURL will return you the ALAsset instance of the newly created asset.

Cheers.

Hendrik

1
votes

Even easier use the following code :

    //Save to photo album
    UIImage *img = [[[UIImage alloc] initWithData:imageData] autorelease];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeImageToSavedPhotosAlbum:img.CGImage
                                 metadata:[info objectForKey:UIImagePickerControllerMediaMetadata]
                          completionBlock:^(NSURL *assetURL, NSError *error) {
                              NSLog(@"assetURL %@", assetURL);
                          }];
1
votes

You can use the UIImageWriteToSavedPhotosAlbum function to save the UIImage to the camera's rollover.

void UIImageWriteToSavedPhotosAlbum (
   UIImage  *image,
   id       completionTarget,
   SEL      completionSelector,
   void     *contextInfo
);

It is described here.

Then you can pick it up from the Asset library.