iPhone - 如何创建自定义相册并以编程方式为相机胶卷中的照片指定自定义名称?

问题描述 投票:15回答:5

我正在开发一个iPhone照片应用程序,所以我需要在相机胶卷中创建一个名为“My Album”的单独相册,我需要在新创建的目录中保存带有自定义名称的UIImageView图像,例如“My Image.png” 。

我怎样才能做到这一点?

iphone ios camera nsfilemanager
5个回答
16
投票

您可以使用iOS中的以下代码行创建自定义相册并轻松添加图像:

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

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

            // add asset
            PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
        } completionHandler:^(BOOL success, NSError *error) {
            if (!success) {
                NSLog(@"Error: %@", error);
            }
        }];
    } else {
        NSLog(@"Error: %@", error);
    }
}];

11
投票

由于AssetsLibrary已被弃用,请使用Photos框架(iOS 8及更高版本)。

// Deprecated!
import AssetsLibrary

// Swift 3.0
let assetsLibrary = ALAssetsLibrary()
assetsLibrary.addAssetsGroupAlbum(withName: "NewAlbum", resultBlock: { assetsGroup in
    print(assetsGroup == nil ? "Already created" : "Success")
}, failureBlock: { error in
    print(error)
})

您可以使用共享的PHPhotoLibrary对象来创建新照片,但是您无法为它们指定具体名称,因为您将使用需要由Photos.app管理的资产。每个资产都有特定的属性。您可以获取对象,请求更改,资产/缩略图加载和缓存等。

要创建自定义相册,请使用PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle:)

简要示例:

// Swift 3.0
func createPhotoLibraryAlbum(name: String) {
    var albumPlaceholder: PHObjectPlaceholder?
    PHPhotoLibrary.shared().performChanges({
        // Request creating an album with parameter name
        let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
        // Get a placeholder for the new album
        albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
    }, completionHandler: { success, error in
        if success {
            guard let placeholder = albumPlaceholder else {
                fatalError("Album placeholder is nil")
            }

            let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
            guard let album: PHAssetCollection = fetchResult.firstObject else {
                // FetchResult has no PHAssetCollection
                return
            }

            // Saved successfully!
            print(album.assetCollectionType)
        }
        else if let e = error {
            // Save album failed with error
        }
        else {
            // Save album failed with no error
        }
    })
}

别忘了import Photos图书馆。

要在该相册上创建新的照片资源,请使用PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle:)

// Swift 3.0
func createPhotoOnAlbum(photo: UIImage, album: PHAssetCollection) {
    PHPhotoLibrary.shared().performChanges({
        // Request creating an asset from the image
        let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: photo)
        // Request editing the album
        guard let albumChangeRequest = PHAssetCollectionChangeRequest(for: album) else {
            // Album change request has failed
            return
        }
        // Get a placeholder for the new asset and add it to the album editing request
        guard let photoPlaceholder = createAssetRequest.placeholderForCreatedAsset else {
            // Photo Placeholder is nil
            return
        }
        albumChangeRequest.addAssets([photoPlaceholder] as NSArray)
    }, completionHandler: { success, error in
        if success {
            // Saved successfully!
        }
        else if let e = error {
            // Save photo failed with error
        }
        else {
            // Save photo failed with no error
        }
    })
}

更新:

我们需要请求访问才能使用照片库:

PHPhotoLibrary.requestAuthorization { status in
     switch status {
     ...
}

从iOS 10及更高版本开始,我们还需要在目标.plist文件中为“隐私 - 照片库使用说明”添加访问条目:

<key>NSPhotoLibraryUsageDescription</key>
<string>Access to photos is needed to provide app features</string>

7
投票

它从iOS 5.0开始运行。 请导入AssetsLibrary / AssetsLibrary.h

ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:@"My Album" resultBlock:^(ALAssetsGroup *group) 
{
    NSLog(@"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
} failureBlock:^(NSError *error) 
{
    NSLog(@"Error: Adding on Folder");
}];

2
投票

制作新相册:

func createAlbum(withTitle title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
    DispatchQueue.global(qos: .background).async {
        var placeholder: PHObjectPlaceholder?

        PHPhotoLibrary.shared().performChanges({
            let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)
            placeholder = createAlbumRequest.placeholderForCreatedAssetCollection
        }, completionHandler: { (created, error) in
            var album: PHAssetCollection?
            if created {
                let collectionFetchResult = placeholder.map { PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [$0.localIdentifier], options: nil) }
                album = collectionFetchResult?.firstObject
            }

            completionHandler(album)
        })
    }
}

获取具有指定名称的相册:

func getAlbum(title: String, completionHandler: @escaping (PHAssetCollection?) -> ()) {
    DispatchQueue.global(qos: .background).async { [weak self] in
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", title)
        let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

        if let album = collections.firstObject {
            completionHandler(album)
        } else {
            self?.createAlbum(withTitle: title, completionHandler: { (album) in
                completionHandler(album)
            })
        }
    }
}

并将照片保存到相册:

func save(photo: UIImage, toAlbum titled: String completionHandler: @escaping (Bool, Error?) -> ()) {
    getAlbum(title: titled) { (album) in
        DispatchQueue.global(qos: .background).async {
            PHPhotoLibrary.shared().performChanges({
                let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: photo)
                let assets = assetRequest.placeholderForCreatedAsset
                    .map { [$0] as NSArray } ?? NSArray()
                let albumChangeRequest = album.flatMap { PHAssetCollectionChangeRequest(for: $0) }
                albumChangeRequest?.addAssets(assets)
            }, completionHandler: { (success, error) in
                completionHandler(success, error)
            })
        }
    }
}

-1
投票

您可以尝试我的以下方法为iOS 7和iOS 8创建相册

#define PHOTO_ALBUM_NAME @"AlbumName Videos"
-(void)createAlbum{

// PHPhotoLibrary_class will only be non-nil on iOS 8.x.x
Class PHPhotoLibrary_class = NSClassFromString(@"PHPhotoLibrary");

if (PHPhotoLibrary_class) {


    // iOS 8..x. . code that has to be called dynamically at runtime and will not link on iOS 7.x.x ...

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:PHOTO_ALBUM_NAME];
    } completionHandler:^(BOOL success, NSError *error) {
        if (!success) {
            NSLog(@"Error creating album: %@", error);
        }else{
            NSLog(@"Created");
        }
    }];
}else{
    [self.library addAssetsGroupAlbumWithName:PHOTO_ALBUM_NAME resultBlock:^(ALAssetsGroup *group) {
        NSLog(@"adding album:'Compressed Videos', success: %s", group.editable ? "YES" : "NO");

        if (group.editable == NO) {
        }

    } failureBlock:^(NSError *error) {
        NSLog(@"error adding album");
    }];
}}
© www.soinside.com 2019 - 2024. All rights reserved.