iOS将照片保存在应用专用相册中

我正在创build一个iOS 5应用程序。 我想将照片保存到设备。

我想将照片保存到特定于我的应用的相册中,因此我需要创build相册,然后将照片保存到相册中。

我知道如何创build相册:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library addAssetsGroupAlbumWithName:@"MY APP NAME" resultBlock:^(ALAssetsGroup *group) { //How to get the album URL? } failureBlock:^(NSError *error) { //Handle the error }]; 

我现在要将照片添加到新相册,我该怎么做? 示例代码非常感谢!

这篇文章似乎用自定义的ALAssetsLibrary类别来实现你正在寻找的ALAssetsLibrary 。 看起来像文章下面有一些有用的评论,也可能有助于performance。

您可能会使用下面的代码,只是更改相册的名称:

 __weak ALAssetsLibrary *lib = self.library; [self.library addAssetsGroupAlbumWithName:@"My Photo Album" resultBlock:^(ALAssetsGroup *group) { ///checks if group previously created if(group == nil){ //enumerate albums [lib enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *g, BOOL *stop) { //if the album is equal to our album if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"My Photo Album"]) { //save image [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) { //then get the image asseturl [lib assetForURL:assetURL resultBlock:^(ALAsset *asset) { //put it into our album [g addAsset:asset]; } failureBlock:^(NSError *error) { }]; }]; } }failureBlock:^(NSError *error){ }]; }else{ // save image directly to library [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) { [lib assetForURL:assetURL resultBlock:^(ALAsset *asset) { [group addAsset:asset]; } failureBlock:^(NSError *error) { }]; }]; } } failureBlock:^(NSError *error) { }]; 

对于任何想要在iOS 9中执行此操作的人来说,事情变得复杂一些,因为ALAssetsLibrary不赞成使用新的Photos库。

下面是一些用于将UIImage添加到特定相册名称的Swift代码(创build相册,如果它不存在),您可能需要为您的需要做一些重构/优化:

 func insertImage(image : UIImage, intoAlbumNamed albumName : String) { //Fetch a collection in the photos library that has the title "albumNmame" let collection = fetchAssetCollectionWithAlbumName(albumName) if collection == nil { //If we were unable to find a collection named "albumName" we'll create it before inserting the image PHPhotoLibrary.sharedPhotoLibrary().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName) }, completionHandler: {(success : Bool, error : NSError?) in if error != nil { print("Error: " + error!.description) } if success { //Fetch the newly created collection (which we *assume* exists here) let newCollection = self.fetchAssetCollectionWithAlbumName(albumName) self.insertImage(image, intoAssetCollection: newCollection!) } } ) } else { //If we found the existing AssetCollection with the title "albumName", insert into it self.insertImage(image, intoAssetCollection: collection!) } } func fetchAssetCollectionWithAlbumName(albumName : String) -> PHAssetCollection? { //Provide the predicate to match the title of the album. let fetchOption = PHFetchOptions() fetchOption.predicate = NSPredicate(format: "title == '" + albumName + "'") //Fetch the album using the fetch option let fetchResult = PHAssetCollection.fetchAssetCollectionsWithType( PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.AlbumRegular, options: fetchOption) //Assuming the album exists and no album shares it's name, it should be the only result fetched let collection = fetchResult.firstObject as? PHAssetCollection return collection } func insertImage(image : UIImage, intoAssetCollection collection : PHAssetCollection) { //Changes for the Photos Library must be maded within the performChanges block PHPhotoLibrary.sharedPhotoLibrary().performChanges({ //This will request a PHAsset be created for the UIImage let creationRequest = PHAssetCreationRequest.creationRequestForAssetFromImage(image) //Create a change request to insert the new PHAsset in the collection let request = PHAssetCollectionChangeRequest(forAssetCollection: collection) //Add the PHAsset placeholder into the creation request. //The placeholder is used because the actual PHAsset hasn't been created yet if request != nil && creationRequest.placeholderForCreatedAsset != nil { request!.addAssets([creationRequest.placeholderForCreatedAsset!]) } }, completionHandler: { (success : Bool, error : NSError?) in if error != nil { print("Error: " + error!.description) } } ) } 

对于那些在Objective-C.寻找Eddy的答案的人Objective-C.

#import <Photos/Photos.h>

 - (void)insertImage:(UIImage *)image intoAlbumNamed:(NSString *)albumName { //Fetch a collection in the photos library that has the title "albumNmame" PHAssetCollection *collection = [self fetchAssetCollectionWithAlbumName: albumName]; if (collection == nil) { //If we were unable to find a collection named "albumName" we'll create it before inserting the image [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle: albumName]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error inserting image into album: %@", error.localizedDescription); } if (success) { //Fetch the newly created collection (which we *assume* exists here) PHAssetCollection *newCollection = [self fetchAssetCollectionWithAlbumName:albumName]; [self insertImage:image intoAssetCollection: newCollection]; } }]; } else { //If we found the existing AssetCollection with the title "albumName", insert into it [self insertImage:image intoAssetCollection: collection]; } } - (PHAssetCollection *)fetchAssetCollectionWithAlbumName:(NSString *)albumName { PHFetchOptions *fetchOptions = [PHFetchOptions new]; //Provide the predicate to match the title of the album. fetchOptions.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"title == '%@'", albumName]]; //Fetch the album using the fetch option PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:fetchOptions]; //Assuming the album exists and no album shares it's name, it should be the only result fetched return fetchResult.firstObject; } - (void)insertImage:(UIImage *)image intoAssetCollection:(PHAssetCollection *)collection { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ //This will request a PHAsset be created for the UIImage PHAssetCreationRequest *creationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:image]; //Create a change request to insert the new PHAsset in the collection PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection]; //Add the PHAsset placeholder into the creation request. //The placeholder is used because the actual PHAsset hasn't been created yet if (request != nil && creationRequest.placeholderForCreatedAsset != nil) { [request addAssets: @[creationRequest.placeholderForCreatedAsset]]; } } completionHandler:^(BOOL success, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error inserting image into asset collection: %@", error.localizedDescription); } }]; } 

https://github.com/amazingmanthere/ZCPhotoLibrary

这是一个简单的工具类,用于保存或删除系统照片库中的资源。