14

iOS 5 アプリを作成しています。写真をデバイスに保存したい。

アプリ固有のアルバムに写真を保存したいので、アルバムを作成してから写真をアルバムに保存する必要があります。

私はアルバムを作成する方法を知っています:

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
}];

今すぐ新しいアルバムに写真を追加したいのですが、どうすればよいですか? サンプルコードは大歓迎です!

4

5 に答える 5

21

次のコードを使用して、アルバムの名前を変更するだけです。

__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) {

}];
于 2013-12-28T17:07:49.607 に答える
11

iOS 9 でこれを行おうとしている人にとっては、ALAssetsLibrary が廃止され、新しい Photos ライブラリが優先されたため、状況は少し複雑になっています。

特定のアルバム名に UIImages を追加する (存在しない場合はアルバムを作成する) ための Swift コードを次に示します。必要に応じてリファクタリング/最適化を行う必要がある場合があります。

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)
            }
        }
    )
}
于 2015-11-19T03:41:10.160 に答える