Gihan
Gihan

Reputation: 2536

Failure when saving to album using ALAssetLibrary

I am trying to save some images that I generate to an album using ALAssetLibrary using ALAssetsLibrary+CustomPhotoAlbum by Marin Todorov. However, I get random failures most of the time.

  // Get the asset library instance.
  ALAssetsLibrary *library = [ALAssetLibraryManager defaultAssetsLibrary];
  [self.imageModels enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // Sidenote: Trying to use an image that I have locally in my image assets fails as well.
    // UIImage *image = [UIImage imageNamed:@"Background-light-png.png"];
    UIImage *image = [UIImage imageWithContentsOfFile:[obj valueForKey:@"imagePath"]];
    [_imagesToShare addObject:image];
    if (image){
        [library saveImage:image toAlbum:@"My Album" completion:^(NSURL assetURL, NSError error) {
            NSLog(@"Success");
        } failure:^(NSError *error) {
            NSLog(@"Failed %@", error.description);
        }];
    }
}];

In the failure block, if I add the following code, I can see that the image gets saved to the Camera Roll.

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

The error I get is

Failed: Error Domain=LIB_ALAssetsLibrary_CustomPhotoAlbum Code=0 "ALAssetsGroup failed to add asset." UserInfo=0x171277c80 {NSLocalizedDescription=ALAssetsGroup failed to add asset.}

Code for getting the asset library

+ (ALAssetsLibrary *)defaultAssetsLibrary {
   static dispatch_once_t pred = 0;
   static ALAssetsLibrary *library = nil;
   dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
   });
   return library;
}

I searched a lot, but couldn't find much on this topic. My method is called from a button click and there should be no other writes happening at the same time. The only info I found online was that you should keep the same ALAssetLibrary instance around, which I have done using the singleton class.

Upvotes: 1

Views: 699

Answers (1)

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

This is how I use asset library to save images:

 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:((UIImage *)[info objectForKey:UIImagePickerControllerEditedImage]).CGImage
                             metadata:[info objectForKey:UIImagePickerControllerMediaMetadata]
                      completionBlock:^(NSURL *assetURL, NSError *error) {
                          NSLog(@"assetURL %@", assetURL);
                            imageURL=[assetURL absoluteString];

                          [[NSUserDefaults standardUserDefaults] setObject:imageURL forKey:@"imageurl"]; //for reference of the path

                      }];

Upvotes: 1

Related Questions