簡體   English   中英

在 iOS 8 中將照片保存到自定義相冊

[英]Save a photo to custom album in iOS 8

我在這里需要一點幫助,我有一個方法可以將 UIImage 保存到相機膠卷,在 iOS 8 中沒有問題。方法如下

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

    }
}];

我需要修改該代碼,以便圖像而不是將 UIImage 保存到相機膠卷,而是保存到名為“MyAlbum”的自定義相冊

我正在使用 Photos.framework

您首先需要通過獲取請求檢查相冊是否存在,然后將圖像添加到相冊或創建相冊然后添加圖像。

目標-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);
            }
        }];
    }
}

斯威夫特 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)")
            }
        }
    }
}

在將資產添加到相冊之前,創建名為“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);
        }
    }];

檢查相冊是否已經存在。

   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

   }

在您的執行更改塊中,您指定請求的 assetCollection

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM