Search code examples
iosobjective-csdwebimage

Using SDWebImage and saving image to public gallery


I am using SDWebImage for my iOS project. SDWebImage has great features to cache the picture in the memory as well as in the disk when extracting pictures based on URL. However, could we also make the pictures (cached by SDWebImage) available in the picture galley? This allows the user to view the picture they downloaded using the photo galley and also allows other apps to use the pictures as well.


Solution

  • You can get the image after SDWebImage loads it into your UIImageView like this:

    [self.imageView sd_setImageWithURL:url
        placeholderImage:placeholder 
        options:options
        progress:nil
        completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image) {
                // save to photo album here
            }
        }
    ];
    

    I use this library to save photos to a custom photo album:

    https://github.com/Kjuly/ALAssetsLibrary-CustomPhotoAlbum

    Here is sample code using this library:

    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary saveImage:image toAlbum:@"YOUR_ALBUM_NAME" completion:nil failure:nil];
    

    Update: You can use the ALAssetsLibrary to load images from the album as well. Here is an example:

    ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary loadImagesFromAlbum:^(NSMutableArray *images, NSError *error) {
        if (images) {
            // ...
        }
    }];