在iOS 8中将照片保存到自定义相册

9

我需要在这里得到一点帮助,我有一个在iOS 8中可以将UIImage保存到相机胶卷的方法。该方法如下:

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

    }
}];

我需要修改那段代码,使得图像保存到一个名为"MyAlbum"的自定义相册中,而不是保存UIImage到相机胶卷中。
我正在使用Photos.framework。

与论坛网站不同,我们在 [so] 上不使用“谢谢”、“感激任何帮助”或签名。请参阅“应该从帖子中删除‘Hi’、‘thanks’、标语和问候语吗? - John Saunders
4个回答

20

您首先需要使用 fetch 请求检查相册是否存在,然后将图片添加到相册中或创建相册,然后再添加图片。

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)")
            }
        }
    }
}

块签名可以是 void (^saveBlock)(PHAssetCollection *) = ^void(PHAssetCollection *assetCollection) - schmidt9

7
在将资产添加到相册之前,使用名称“ MyAlbum”创建新相册。
    // 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
我们应该检查一下这个集合的名称是否已经存在,还是框架已经处理了这个问题? - Andy Ibanez
1
除了@AndyIbanez所说的之外,我可以确认这种方法不会检查相册是否存在,并且每次以这种方式保存照片时都会创建一个新的相册。 - Jake
应用程序被杀死后如何获取相册? - Priyal

0
检查相册是否已存在。
   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

   }

-1
在你的“执行更改”块中,你需要指定请求的assetCollection。 let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(-YOUR ALBUM NAME-)

我应该更改哪个执行更改的块? - Vijay Masal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接