IOS applications save pictures to apply custom albums

In many applications, browse pictures, pictures can long press to select the save to mobile phone album custom name album, such as micro-blog, it will automatically create a “micro-blog” album in the album, and add to save the picture to the. After iOS8, we can use the Photos framework to implement this functionality very easily.

If you want to meet the previous version of iOS8, you can use the AssetsLibrary framework, but this framework has been abandoned after iOS9.

First, Photos framework briefly introduced

1, important classes

The framework has several very important classes: PHAsset, PHAssetCollection, and PHLibrary.

PHAsset said a picture or video files
PHAssetCollection said the collection of images or video collection, actually refers to the album (including the album and custom photo album)
PHLibrary said that the whole album library, including the entire picture album and etc.

2 query operations

Query operations, using the methods of the PHAsset and PHAssetCollection classes themselves

//1 gets the pictures in the album — ID—, which passes in the album picture, returns a set of pictures

[PHAsset fetchAssetsWithLocalIdentifiers:@[ID] options:nil];

//2 queries all albums in the phone list (divided into system albums and custom albums, through the control of the incoming parameters to determine) – back to album group – similar array -forin traversal can be

[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

3, additions and deletions to the operation

  1. If the query operations outside, for example, save the picture to create custom photo albums, add a picture to the custom album, require the use of other two types: PHAssetChangeRequest and PHAssetCollectionChangeRequest
  2. These operations must be called in the middle of the [[PHPhotoLibrary sharedPhotoLibrary]performChange…] block

//1 save pictures

[PHAssetChangeRequest creationRequestForAssetFromImage:image];

//2 create album

[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@ "custom album"];

Two, save pictures to custom album

1, determine album access rights

When you save a picture, let’s first determine if the application has access to the album. This can be easily judged by the following code:

- (BOOL) achiveAuthorizationStatus{/ / 1, determine the album access PHAuthorizationStatusNotDetermined = 0 / * *, not on the user permissions for the application to choose * PHAuthorizationStatusRestricted, this application is authorized to access the data without a picture. Maybe it's parental control. * PHAuthorizationStatusDenied, users have explicitly rejected the application to access the photo data. * PHAuthorizationStatusAuthorized, the user has authorized the application access to the photo data. * / PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus]; if (status = = PHAuthorizationStatusDenied || status = = PHAuthorizationStatusRestricted) {/ / *authorizationAlert = [UIAlertController alertControllerWithTitle:@ UIAlertController no permission to "tip" message:@ "no photos of access. Please open the" settings in preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@ style:UIAlertActionStyleCancel handler:NULL] [authorizationAlert "OK"; addAction:cancel]; [self, presentViewController:authorizationAlert, animated:YES, completion:nil]; return NO;} else {return YES;}

2, save the picture to the system album

For the preservation of images or videos to a custom photo album, is actually the first album will be saved to the system, the reference to a custom picture album we create, save the picture or video of a total of three ways, the following code:

- (void) saveImageFromImage: (UIImage *) image{_saveType = 0; _targetImage = image; [self saveIntoAlbum];} - (void) saveImageFromFileURL: (NSURL *) url{_saveType = 1; _targetImageURL = URL; [self saveIntoAlbum];} - (void) saveVideoFromFileURL: (NSURL *) url{_saveType = 2; _targetVideoURL = URL; [self saveIntoAlbum]}; - (void) saveIntoAlbum{/ / 1, judge [PHPhotoLibrary requestAuthorization:^ album access (PHAuthorizationStatus status) {if (status! = PHAuthorizationStatusAuthorized) {NSError} / / no permissions return; *error = nil; / / 2, permissions, save photos to __block PHObjectPlaceholder *targetObject = nil camera film; __weak typeof (self) weakself = self; switch (_saveType) case 0:{[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{targetObject {[PHAssetCreationRequest} = creationRequestForAssetFromImage:_targetImage].placeholderForCreatedAsset; error:& error]; break; case 1:{[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{targetObject}} = [PHAssetCreationRequest creationRequestForAssetFromImageAtFileURL:_targetImageURL].placeholderForCreatedAsset; error:& error]; break; case 2:{[[PHPhotoLi} Brary sharedPhotoLibrary] performChangesAndWait:^{targetObject = [PHAssetCreationRequest creationRequestForAssetFromVideoAtFileURL:_targetVideoURL].placeholderForCreatedAsset; error:& error] break;};}}; default: break; if (error) {NSLog (@ "save failed:% @", error); return;} / / TODO: will be saved to the system image or video reference to a custom}] album;}

3. Create / get custom albums

To save a picture to a custom album, before you save it, you need to retrieve the album object we created. If you do not get it, then create the code as follows:

Get the name as a custom application / / #define albumName [NSBundle album mainBundle].infoDictionary[(NSString *) - kCFBundleNameKey] (PHAssetCollection * createdCollection) {/ / get all the custom album PHFetchResult< PHAssetCollection; *> collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular * options:nil]; for (PHAssetCollection *collection in collections if ([collection.localizedTitle isEqualToString:albumName]) {collection} {return}); / / code perform here, it is not the custom album __block NSString *createdCollectionId = nil; / / create a new album [[PHPhotoLibrary share DPhotoLibrary] performChangesAndWait:^{createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier error:nil];}; if (createdCollectionId = = Nil) return nil; / / create after removing [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] album return options:nil].firstObject;}

4, save to custom album

As mentioned above, after the above steps have been completed, you can save them to your custom album through the following code:

- (void) saveImageToCustomAlbum{/ / 3, get a custom object PHAssetCollection *collection createdCollection] = [self album; if (collection = = Nil) return; 4, [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{/ / save "PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection] insertAssets:@[targetObject] atIndexes:[NSIndexSet indexSetWithIndex:0]]; error:& error];}; if (error) {NSLog (@" save failed:% @ ", error); else {NSLog} (@" save ");}}