SoFunction
Updated on 2025-04-12

How to save photos to albums on iOS

This article has shared the specific code for saving photos to the album on iOS for your reference. The specific content is as follows

Please import before use

Then import

#import <Photos/>
#import <Photos/>
#import <Photos/>

Method 1

Save the image to the album using UIImageWriteToSavedPhotosAlbum function, such as:

- (void)loadImageFinished:(UIImage *)image
{
  UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
  NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

The first parameter is the image object to be saved to the album

The second parameter is to save the target object called back after the completion

The third parameter is which method to call back to the target object after saving is completed. The method declaration should be as shown in the code:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

After the fourth parameter is saved, it will be passed back to the contextInfo parameter of the callback method intact.

Method 2

Use the ALAssetsLibrary class in the AssetsLibrary framework to implement it. The specific code is as follows:

- (void)loadImageFinished:(UIImage *)image
{
  __block ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  [lib writeImageToSavedPhotosAlbum: metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {

    NSLog(@"assetURL = %@, error = %@", assetURL, error);
    lib = nil;

  }];
}

The writeImageToSavedPhotosAlbum:metadata:completionBlock: method of the ALAssetsLibrary class is implemented. The first parameter is an object of CGImageRef, indicating the image to be passed in. The second parameter is some properties of the image, which is not set here so nil is passed in. The last completionBlock is the callback after saving is completed. In this callback, you can get the saved image path and the error message when the save fails.

Notice:Importing is required when using this class. Moreover, this class needs to be used above iOS 4.0, but it is marked as an outdated method after iOS 9.0. The official suggests that PHPhotoLibrary is used instead, which is the third method mentioned below.

Method 3

Use the PHPhotoLibrary class of the Photos framework to implement the save to album function. The code is as follows:

- (void)loadImageFinished:(UIImage *)image
{
  [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

     /Write pictures to album
     PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];


   } completionHandler:^(BOOL success, NSError * _Nullable error) {

     NSLog(@"success = %d, error = %@", success, error);

  }];
}

In this example, first call the performChanges:completionHandler: method of the PHPhotoLibrary class, and then in its changeBlock, pass an image object through the creationRequestForAssetFromImage: method of the PHAssetChangeRequest class to realize the function of saving to the album. Then the completionHandler will tell us whether the operation is successful.

Advanced use:Get the image object saved to the album

Maybe someone needs to get the PHAsset object of the picture after saving the album to perform subsequent operations (I happened to encounter such a problem yesterday). So, here is an improvement to the above example. After creating a PHAssetChangeRequest, save the localIdentifier property of its placeholderForCreatedAsset property to an array, and wait for the operation to complete before searching for the image object you just added through this array. Please see the chestnut below:

- (void)loadImageFinished:(UIImage *)image
{
  NSMutableArray *imageIds = [NSMutableArray array];
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

      //Write the picture to the album      PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
      //Record the local identity and wait for completion to get the image object in the album      [imageIds addObject:];


    } completionHandler:^(BOOL success, NSError * _Nullable error) {

      NSLog(@"success = %d, error = %@", success, error);

      if (success)
      {
        //After successful, take the image object in the album        __block PHAsset *imageAsset = nil;
        PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:imageIds options:nil];
        [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

          imageAsset = obj;
          *stop = YES;

        }];

        if (imageAsset)
        {
          //Load picture data          [[PHImageManager defaultManager] requestImageDataForAsset:imageAsset
             options:nil
             resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {

                NSLog("imageData = %@", imageData);

             }];
        }
      }

    }];
}

Summarize

The first method is the most commonly used, it is very convenient to use, just pass in UIImage, and you don’t need to worry about different versions of iOS. The only disadvantage is that the corresponding added image cannot be found.

The second method is added after iOS4, and it is not recommended to use after iOS9. It also provides a very intuitive way to save pictures, and can also get the corresponding picture path after saving.

The third method is added after iOS8. Its use is a little more complicated, but it allows batch operations, such as adding, modifying, deleting, etc. If you want to do more complex operations, this method is a more recommended way.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.