Save a photo to custom album in iOS 8

2020-08-20 08:31发布

I need a little bit of help in here, I have a method that saves an UIImage to the camera roll without problems in iOS 8. The method is the following

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
}completionHandler:^(BOOL success, NSError *error) {
    if(success){
        NSLog(@"worked");
    }else{
        NSLog(@"Error: %@", error);

    }
}];

I need to adapt that code, so that the image instead of saving the UIImage to the camera roll, it saves to a custom album named "MyAlbum"

I'm using the Photos.framework

4条回答
做自己的国王
2楼-- · 2020-08-20 08:47

In your perform changes block, you specify the request's assetCollection

let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(-YOUR ALBUM NAME-)

查看更多
劳资没心,怎么记你
3楼-- · 2020-08-20 08:48

Create new album with name "MyAlbum" before adding a asset into the album.

    // Create new album.
    __block PHObjectPlaceholder *albumPlaceholder;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection;
    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil];
            PHAssetCollection *assetCollection = fetchResult.firstObject;

            // Add it to the photo library
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

                PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
            } completionHandler:^(BOOL success, NSError *error) {
                if (!success) {
                    NSLog(@"Error creating asset: %@", error);
                }
            }];
        } else {
            NSLog(@"Error creating album: %@", error);
        }
    }];
查看更多
不美不萌又怎样
4楼-- · 2020-08-20 09:09

Check if album already exist.

   NSString *localIdentifier;

   PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

   for (PHAssetCollection *assetCollection in assetCollections) {
       if([[assetCollection localizedTitle] isEqualToString:album]  ){
           localIdentifier = assetCollection.localIdentifier;
           break;
       }

   }

   if(localIdentifier ){
        ///fetch album 
        PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[localIdentifier] options:nil];

   }else{
       ///creat album here

   }
查看更多
神经病院院长
5楼-- · 2020-08-20 09:10

You will first need to check that the album exists with a fetch request, and then either add the image to the album or create the album and then add the image.

Objective-C

#import <Photos/Photos.h>

- (void)saveToAlbum:(UIImage *)image {
    NSString *albumName = @"MyAlbum";

    void (^saveBlock)(PHAssetCollection *assetCollection) = ^void(PHAssetCollection *assetCollection) {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];

        } completionHandler:^(BOOL success, NSError *error) {
            if (!success) {
                NSLog(@"Error creating asset: %@", error);
            }
        }];
    };

    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"localizedTitle = %@", albumName];
    PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:fetchOptions];
    if (fetchResult.count > 0) {
        saveBlock(fetchResult.firstObject);
    } else {
        __block PHObjectPlaceholder *albumPlaceholder;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName];
            albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection;

        } completionHandler:^(BOOL success, NSError *error) {
            if (success) {
                PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil];
                if (fetchResult.count > 0) {
                    saveBlock(fetchResult.firstObject);
                }
            } else {
                NSLog(@"Error creating album: %@", error);
            }
        }];
    }
}

Swift 5

import Photos

func saveToAlbum(image: UIImage) {
    let albumName = "MyAlbum"

    let saveBlock: (PHAssetCollection) -> Void = { assetCollection in
        PHPhotoLibrary.shared().performChanges({
            let assetChangeRequest: PHAssetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            guard let placeholder = assetChangeRequest.placeholderForCreatedAsset else { return }
            guard let assetCollectionChangeRequest: PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection) else { return }
            assetCollectionChangeRequest.addAssets(NSArray(object: placeholder))
        }) { (success, error) in
            if let error = error {
                print("Error creating asset: \(error)")
            }
        }
    }

    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "localizedTitle = %@", albumName)
    let fetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    if fetchResult.count > 0, let collection = fetchResult.firstObject {
        saveBlock(collection)
    } else {
        var albumPlaceholder: PHObjectPlaceholder? = nil
        PHPhotoLibrary.shared().performChanges({
            let changeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
            albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection
        }) { (success, error) in
            if success, let albumPlaceholder = albumPlaceholder {
                let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)
                if fetchResult.count > 0, let collection = fetchResult.firstObject {
                    saveBlock(collection)
                }
            } else if let error = error {
                print("Error creating album: \(error)")
            }
        }
    }
}
查看更多
登录 后发表回答