iOS method of saving photos in App to a system album or self built album

  • 2020-06-01 11:02:00
  • OfStack

Save the photos to the system album
Saving photos to the system album is a function that many social networking APP have. Today we will briefly explain how to save photos to the system album (Photo Album).

1. Create UIImageView

UIImageView was created to display the photos. We want to save UIImage to the system album (Photo Album) :


#define SCREEN [UIScreen mainScreen].bounds.size self.image = [UIImage imageNamed:@"iOSDevTip"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN.width - 300) / 2, 70, 300, 150)];
imageView.image = self.image;
[self.view addSubview:imageView];

2. Create UIButton

Create UIButton and bind actionClick: event:


UIButton *button = [[UIButton alloc] init];
button.frame = CGRectMake( 100, 300, SCREEN.width - 200, 40);
[button addTarget:self action:@selector(actionClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor orangeColor]];
[button setTitle:@"SavePhoto" forState:UIControlStateNormal];
[self.view addSubview:button];
- (void)actionClick:(UIButton *)button
{ }

3. Save photos to the system album (Photo Album)

Call: in the actionClick: method:


UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

At this point, we want to know if the save was successful, so we need to formulate a callback method

// Specify the callback method
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if(!error){
        NSLog(@"save success");
    }else{
        NSLog(@"save failed");
    }
}

In this method, we know if the photo was saved successfully.

Save the photos to the album you created

Next, we will explain in detail 1 about the system album access, save photos, create their own album and so on.

1. Create your own photo album

This is also a comparison creation method, create your own photo album, and then save photos or videos to your own photo album. The relevant code is as follows:


  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:@"test" resultBlock:^(ALAssetsGroup *group) {     // The album was created successfully } failureBlock:^(NSError *error) {
    // failure
}];

Save the photo

This method also saves the photos to the system album, not to the album you created. The code is as follows:


 ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *asSetUrl,NSError *error){
    if (error) {
       // failure
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@" Store successful "
                                                       message:nil
                                                      delegate:nil
                                             cancelButtonTitle:@" determine "
                                             otherButtonTitles:nil, nil];
        [alert show];     }
}];

3. Get permission
If the user turns off album permissions before saving the photo, the save fails. If you don't do anything, the user won't know they failed to save. So, we can make the corresponding prompt before saving the photo. How do I get this permission? There are two methods:

(1) failed to create album

(2) failed to save the photo

In the above two methods to create their own photo album and save the results of the failure of the photo, we can pop up the photo access failed to get a hint. Let's take the example of the first album creation failure:


ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:@"test" resultBlock:^(ALAssetsGroup *group)    {       // The album was created successfully } failureBlock:^(NSError *error) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@" Storage failure "
                                                       message:@" Please open the Set up the - privacy - photo To set it up "
                                                      delegate:nil
                                             cancelButtonTitle:@" determine "
                                             otherButtonTitles:nil, nil];
    [alert show];
}];

In the result of failure to save photos, we can also pop up the corresponding prompt to open the album permissions of the application.

Save your photos to your own album

The following code is found in the big Google, which can be used after testing. It is sorted as follows:


#pragma mark - Create photo albums
- (void)createAlbum
{
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    NSMutableArray *groups=[[NSMutableArray alloc]init];
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group)
        {
            [groups addObject:group];
        }         else
        {
            BOOL haveHDRGroup = NO;             for (ALAssetsGroup *gp in groups)
            {
                NSString *name =[gp valueForProperty:ALAssetsGroupPropertyName];                 if ([name isEqualToString:@"iOSDevTip"])
                {
                    haveHDRGroup = YES;
                }
            }             if (!haveHDRGroup)
            {
                //do add a group named "XXXX"
                [assetsLibrary addAssetsGroupAlbumWithName:@"iOSDevTip"
                                               resultBlock:^(ALAssetsGroup *group)
                 {
                     [groups addObject:group];                  }
                                              failureBlock:nil];
                haveHDRGroup = YES;
            }
        }     };
    // Create a photo album
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:listGroupBlock failureBlock:nil];     [self saveToAlbumWithMetadata:nil imageData:UIImagePNGRepresentation(self.image) customAlbumName:@"iOSDevTip" completionBlock:^
     {
         // Here you can create a method that adds success      }
                     failureBlock:^(NSError *error)
     {
         // Handle the display of the add failed method alert Let it return to the main thread execution, otherwise the box will not pop out
         dispatch_async(dispatch_get_main_queue(), ^{              // Add failure 1 Generally, it is caused by the user not allowing the application to access the album. You can take out this case to judge 1 Under the
             if([error.localizedDescription rangeOfString:@"User denied access"].location != NSNotFound ||[error.localizedDescription rangeOfString:@" User denied access "].location!=NSNotFound){
                 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:error.localizedDescription message:error.localizedFailureReason delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles: nil];                  [alert show];
             }
         });
     }];
} - (void)saveToAlbumWithMetadata:(NSDictionary *)metadata
                      imageData:(NSData *)imageData
                customAlbumName:(NSString *)customAlbumName
                completionBlock:(void (^)(void))completionBlock
                   failureBlock:(void (^)(NSError *error))failureBlock
{     ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    __weak ALAssetsLibrary *weakSelf = assetsLibrary;
    void (^AddAsset)(ALAssetsLibrary *, NSURL *) = ^(ALAssetsLibrary *assetsLibrary, NSURL *assetURL) {
        [assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {                 if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:customAlbumName]) {
                    [group addAsset:asset];
                    if (completionBlock) {
                        completionBlock();
                    }
                }
            } failureBlock:^(NSError *error) {
                if (failureBlock) {
                    failureBlock(error);
                }
            }];
        } failureBlock:^(NSError *error) {
            if (failureBlock) {
                failureBlock(error);
            }
        }];
    };
    [assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
        if (customAlbumName) {
            [assetsLibrary addAssetsGroupAlbumWithName:customAlbumName resultBlock:^(ALAssetsGroup *group) {
                if (group) {
                    [weakSelf assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                        [group addAsset:asset];
                        if (completionBlock) {
                            completionBlock();
                        }
                    } failureBlock:^(NSError *error) {
                        if (failureBlock) {
                            failureBlock(error);
                        }
                    }];
                } else {
                    AddAsset(weakSelf, assetURL);
                }
            } failureBlock:^(NSError *error) {
                AddAsset(weakSelf, assetURL);
            }];
        } else {
            if (completionBlock) {
                completionBlock();
            }
        }
    }];
}


Related articles: