iOS将照片保存在特定应用专辑中

时间:2012-08-15 15:20:51

标签: iphone objective-c ios camera alassetslibrary

我正在创建一个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
}];

我想现在为新专辑添加照片,我该怎么办?非常感谢示例代码!

5 个答案:

答案 0 :(得分: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) {

}];

答案 1 :(得分:11)

对于那些希望在iOS 9中执行此操作的人来说,由于不推荐使用ALAssetsLibrary以支持新的照片库,因此事情变得更加复杂。

这里有一些用于将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)
            }
        }
    )
}

答案 2 :(得分:9)

对于那些在Objective-C.

中寻找Eddy答案的人

#import <Photos/Photos.h>

- (void)insertImage:(UIImage *)image intoAlbumNamed:(NSString *)albumName {
    //Fetch a collection in the photos library that has the title "albumNmame"
    PHAssetCollection *collection = [self 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:^(BOOL success, NSError * _Nullable error) {
            if (error != nil) {
                NSLog(@"Error inserting image into album: %@", error.localizedDescription);
            }

            if (success) {
                //Fetch the newly created collection (which we *assume* exists here)
                PHAssetCollection *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];
    }
}

- (PHAssetCollection *)fetchAssetCollectionWithAlbumName:(NSString *)albumName {
    PHFetchOptions *fetchOptions = [PHFetchOptions new];
    //Provide the predicate to match the title of the album.
    fetchOptions.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"title == '%@'", albumName]];

    //Fetch the album using the fetch option
    PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:fetchOptions];

    //Assuming the album exists and no album shares it's name, it should be the only result fetched
    return fetchResult.firstObject;
}

- (void)insertImage:(UIImage *)image intoAssetCollection:(PHAssetCollection *)collection {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

        //This will request a PHAsset be created for the UIImage
        PHAssetCreationRequest *creationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:image];

        //Create a change request to insert the new PHAsset in the collection
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection: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:^(BOOL success, NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Error inserting image into asset collection: %@", error.localizedDescription);
        }
    }];
}

答案 3 :(得分:0)

Eddy对Swift 4答案的适应:

* def toTime1 =
    """
    function(s) {
      var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
      var sdf = new SimpleDateFormat("yyyy-MM-dd");
      return sdf.parse(s).time           
    }
    """
* def toTime2 =
    """
    function(s) {
      var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
      var sdf = new SimpleDateFormat("dd-MM-yyyy");
      return sdf.parse(s).time           
    }
    """  
* def input = toTime2("24-11-2018")
* def today = new java.util.Date().time
* def isValid1 = function(x){ return toTime1(x) < today  }
* def isValid2 = function(x){ return toTime2(x) < input  }

* def response = [{ date1: "2018-12-23", date2: "23-11-2018" }, { date1: "2018-12-20", date2: "23-11-2018" }]
* match each response == { date1: '#? isValid1(_)', date2: '#? isValid2(_)' }

答案 4 :(得分:0)

使用块的目标C的改进版本。它创建一个相册(如果不存在),然后保存三种类型的媒体项目-照片,GIF和视频:

// Types of media, that can be saved to an album
typedef NS_ENUM(NSUInteger, AlbumMediaType) {
    AlbumMediaTypePhoto,
    AlbumMediaTypeGIF,
    AlbumMediaTypeVideo
};

/**
 Creates album if it doesn't exist and returns it in a block
 */
- (void)createCollectionOnComplete:(void (^ _Nonnull)(PHAssetCollection * _Nonnull collection))onComplete
{
    NSString *albumTitle = @"YOUR_ALBUM_TITLE";

    __block PHAssetCollection *collection;
    __block PHObjectPlaceholder *placeholder;

    // Searching for an existing album
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", albumTitle];
    collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                          subtype:PHAssetCollectionSubtypeAny
                                                          options:fetchOptions].firstObject;
    // If album is not found, we create it
    if (!collection)
    {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *createAlbum = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumTitle];
            placeholder = [createAlbum placeholderForCreatedAssetCollection];
        } completionHandler:^(BOOL success, NSError *error) {
            if (success)
            {
                PHFetchResult *collectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[placeholder.localIdentifier]
                                                                                                            options:nil];
                collection = collectionFetchResult.firstObject;
                // After creating album, we return it
                onComplete(collection);
            }
        }];
    } else {
        // If album already exists, we instantly return it
        onComplete(collection);
    }
}


/**
 Saves an item of a given mediatype, that is located in mediaURL
 */
- (void)saveToAlbumMediaItemFromURL:(NSURL *)mediaURL mediaType:(AlbumMediaType)mediaType
{
    NSData *mediaData = [NSData dataWithContentsOfURL:mediaURL];
    if (!mediaData) {
        OWSFail(@"%@ Could not load data: %@", self.logTag, [self.attachmentStream mediaURL]);
        return;
    }

    [self createCollectionOnComplete:^(PHAssetCollection * _Nonnull collection) {

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

            // We create a PHAsset using creationRequest
            PHAssetCreationRequest *assetRequest;
            switch (mediaType) {
                case AlbumMediaTypePhoto: {
                    assetRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:[UIImage imageWithData:mediaData]];
                    break;
                }
                case AlbumMediaTypeGIF: {
                    assetRequest = [PHAssetCreationRequest creationRequestForAsset];
                    PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
                    [assetRequest addResourceWithType:PHAssetResourceTypePhoto data:mediaData options:options];
                    break;
                }
                case AlbumMediaTypeVideo: {
                    if ( !UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(mediaURL.path) ) {
                        OWSFail(@"%@ Could not save incompatible video data.", self.logTag);
                        break;
                    }

                    NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"];
                    [mediaData writeToFile:videoPath atomically:YES];
                    assetRequest = [PHAssetCreationRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:videoPath]];
                    break;
                }
                default:
                    break;
            }

            // Creating a request to change an album
            PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];

            // PHAsset is not created yet, so we use a placeholder
            PHObjectPlaceholder *placeholder = [assetRequest placeholderForCreatedAsset];

            // We add a placeholder of a created item to the request of changing album
            if (albumChangeRequest != nil && placeholder != nil) {
                [albumChangeRequest addAssets: @[placeholder]];
            }

        } completionHandler:^(BOOL success, NSError *error) {

            if (success) {
                NSLog(@"Media item saved!");
            } else {
                NSLog(@"Error saving media item - %@", error ? error.localizedDescription : @"");
            }

        }];

    }];
}

我们可以使用以下方法以这种方式保存媒体项目:

[self saveToAlbumMediaItemFromURL:[self.attachmentStream mediaURL] mediaType:AlbumMediaTypeGIF];