iOS SDK 如何从自定义相册中获取图片?
How to get images from Custom album of Photos, iOS SDK?
我正在开发一个 iOS 应用程序,我需要在其中使用像 Instagram 这样的画廊视图。我添加了画廊视图、相机视图和视频视图,拍摄图像后将其保存到照片的自定义相册中。现在我想从自定义相册中检索这些图像并将其显示到图库的 Collection 视图。但我无法从自定义相册中检索这些图像。任何帮助将不胜感激。
编辑:
我添加了用于创建自定义相册的 PHPhotoLibrary,在此之前我添加了 AssetsLibrary 框架。
然后我创建了一个 NSObject class (CustomAlbum) 用于使用 PHPhotoLibrary 创建和管理自定义相册。
// CustomAlbum.h
#import <Foundation/Foundation.h>
#import <Photos/Photos.h>
@interface CustomAlbum : NSObject
//Creating album with given name
+(void)makeAlbumWithTitle:(NSString *)title onSuccess:(void(^)(NSString *AlbumId))onSuccess onError: (void(^)(NSError * error)) onError;
//Get the album by name
+(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName;
//Add a image
+(void)addNewAssetWithImage:(UIImage *)image toAlbum:(PHAssetCollection *)album onSuccess:(void(^)(NSString *ImageId))onSuccess onError: (void(^)(NSError * error)) onError;
//get the image using identifier
+ (void)getImageWithIdentifier:(NSString*)imageId onSuccess:(void(^)(UIImage *image))onSuccess onError: (void(^)(NSError * error)) onError;
@end
// CustomAlbum.m
#import "CustomAlbum.h"
@implementation CustomAlbum
#pragma mark - PHPhoto
+(void)makeAlbumWithTitle:(NSString *)title onSuccess:(void(^)(NSString *AlbumId))onSuccess onError: (void(^)(NSError * error)) onError
{
//Check weather the album already exist or not
if (![self getMyAlbumWithName:title]) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// Request editing the album.
PHAssetCollectionChangeRequest *createAlbumRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
// Get a placeholder for the new asset and add it to the album editing request.
PHObjectPlaceholder * placeHolder = [createAlbumRequest placeholderForCreatedAssetCollection];
if (placeHolder) {
onSuccess(placeHolder.localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(@"Finished adding asset. %@", (success ? @"Success" : error));
if (error) {
onError(error);
}
}];
}
}
+(void)addNewAssetWithImage:(UIImage *)image toAlbum:(PHAssetCollection *)album onSuccess:(void(^)(NSString *ImageId))onSuccess onError: (void(^)(NSError * error)) onError
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// Request creating an asset from the image.
PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// Request editing the album.
PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:album];
// Get a placeholder for the new asset and add it to the album editing request.
PHObjectPlaceholder * placeHolder = [createAssetRequest placeholderForCreatedAsset];
[albumChangeRequest addAssets:@[ placeHolder ]];
NSLog(@"%@",placeHolder.localIdentifier);
if (placeHolder) {
onSuccess(placeHolder.localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(@"Finished adding asset. %@", (success ? @"Success" : error));
if (error) {
onError(error);
}
}];
}
+(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName
{
#if 0
NSString * identifier = [[NSUserDefaults standardUserDefaults]objectForKey:kAlbumIdentifier];
if (!identifier) return nil;
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[identifier]
options:nil];
#else
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAlbumRegular
options:nil];
#endif
NSLog(@"assetCollections.count = %lu", assetCollections.count);
if (assetCollections.count == 0) return nil;
__block PHAssetCollection * myAlbum;
[assetCollections enumerateObjectsUsingBlock:^(PHAssetCollection *album, NSUInteger idx, BOOL *stop) {
NSLog(@"album:%@", album);
NSLog(@"album.localizedTitle:%@", album.localizedTitle);
if ([album.localizedTitle isEqualToString:AlbumName]) {
myAlbum = album;
*stop = YES;
}
}];
if (!myAlbum) return nil;
return myAlbum;
}
+(NSArray *)getAssets:(PHFetchResult *)fetch
{
__block NSMutableArray * assetArray = NSMutableArray.new;
[fetch enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
NSLog(@"asset:%@", asset);
[assetArray addObject:asset];
}];
return assetArray;
}
+ (void)getImageWithIdentifier:(NSString*)imageId onSuccess:(void(^)(UIImage *image))onSuccess onError: (void(^)(NSError * error)) onError
{
NSError *error = [[NSError alloc] init];
PHFetchResult *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[imageId] options:nil];
if (assets.count == 0) onError(error);
NSArray * assetArray = [self getAssets:assets];
PHImageManager *manager = [PHImageManager defaultManager];
CGRect screenRect = [[UIScreen mainScreen] bounds];
[manager requestImageForAsset:assetArray.firstObject targetSize:screenRect.size contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
onSuccess(result);
}];
}
@end
然后使用此方法点击图片按钮创建自定义相册并将图像保存在该自定义相册中。
// Take Image Button Method
- (void)snapButtonPressed:(UIButton *)button
{
[self.camera capture:^(LLSimpleCamera *camera, UIImage *image,
NSDictionary *metadata, NSError *error)
{
if(!error)
{
NSString * info = [NSString stringWithFormat:@"Size: %@ - Orientation: %ld", NSStringFromCGSize(image.size), (long)image.imageOrientation];
[CustomAlbum addNewAssetWithImage:image toAlbum:[CustomAlbum getMyAlbumWithName:CSAlbum] onSuccess:^(NSString *ImageId) {
NSLog(@"%@",ImageId);
recentImg = ImageId;
} onError:^(NSError *error) {
NSLog(@"probelm in saving image");
}];
}
else
{
NSLog(@"An error has occured: %@", error);
}
}
exactSeenImage:YES];
}
这是有效的代码。
__block PHAssetCollection *collection;
// Find the album
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", @"YOUR_CUSTOM_ALBUM_NAME"];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchOptions].firstObject;
PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
[collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//add assets to an array for later use in the uicollectionviewcell
}];
只需尝试一次此代码。您可以使用此代码将所有图像放在一个数组中:-
-(void)getAllPictures
{
__block PHAssetCollection *collection;
// Find the album
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", @"YOUR_CUSTOM_ALBUM_NAME"];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchOptions].firstObject;
PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
NSMutableArray *assets = [[NSMutableArray alloc] init];
[collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
[assets addObject:asset];
}];
PHImageRequestOptions * requestOptions = [[PHImageRequestOptions alloc] init];
//requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
//requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
//requestOptions.synchronous = true;
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[assets count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in assets) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize//CGSizeMake(300, 300)
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
NSLog(@"images %@", images); //You will get all images into this images array.
}
详情请参考Example app using Photos framework。
希望,这就是您要找的。有任何疑虑,请回复我。 :)
我正在开发一个 iOS 应用程序,我需要在其中使用像 Instagram 这样的画廊视图。我添加了画廊视图、相机视图和视频视图,拍摄图像后将其保存到照片的自定义相册中。现在我想从自定义相册中检索这些图像并将其显示到图库的 Collection 视图。但我无法从自定义相册中检索这些图像。任何帮助将不胜感激。
编辑: 我添加了用于创建自定义相册的 PHPhotoLibrary,在此之前我添加了 AssetsLibrary 框架。
然后我创建了一个 NSObject class (CustomAlbum) 用于使用 PHPhotoLibrary 创建和管理自定义相册。
// CustomAlbum.h
#import <Foundation/Foundation.h>
#import <Photos/Photos.h>
@interface CustomAlbum : NSObject
//Creating album with given name
+(void)makeAlbumWithTitle:(NSString *)title onSuccess:(void(^)(NSString *AlbumId))onSuccess onError: (void(^)(NSError * error)) onError;
//Get the album by name
+(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName;
//Add a image
+(void)addNewAssetWithImage:(UIImage *)image toAlbum:(PHAssetCollection *)album onSuccess:(void(^)(NSString *ImageId))onSuccess onError: (void(^)(NSError * error)) onError;
//get the image using identifier
+ (void)getImageWithIdentifier:(NSString*)imageId onSuccess:(void(^)(UIImage *image))onSuccess onError: (void(^)(NSError * error)) onError;
@end
// CustomAlbum.m
#import "CustomAlbum.h"
@implementation CustomAlbum
#pragma mark - PHPhoto
+(void)makeAlbumWithTitle:(NSString *)title onSuccess:(void(^)(NSString *AlbumId))onSuccess onError: (void(^)(NSError * error)) onError
{
//Check weather the album already exist or not
if (![self getMyAlbumWithName:title]) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// Request editing the album.
PHAssetCollectionChangeRequest *createAlbumRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
// Get a placeholder for the new asset and add it to the album editing request.
PHObjectPlaceholder * placeHolder = [createAlbumRequest placeholderForCreatedAssetCollection];
if (placeHolder) {
onSuccess(placeHolder.localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(@"Finished adding asset. %@", (success ? @"Success" : error));
if (error) {
onError(error);
}
}];
}
}
+(void)addNewAssetWithImage:(UIImage *)image toAlbum:(PHAssetCollection *)album onSuccess:(void(^)(NSString *ImageId))onSuccess onError: (void(^)(NSError * error)) onError
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// Request creating an asset from the image.
PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// Request editing the album.
PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:album];
// Get a placeholder for the new asset and add it to the album editing request.
PHObjectPlaceholder * placeHolder = [createAssetRequest placeholderForCreatedAsset];
[albumChangeRequest addAssets:@[ placeHolder ]];
NSLog(@"%@",placeHolder.localIdentifier);
if (placeHolder) {
onSuccess(placeHolder.localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(@"Finished adding asset. %@", (success ? @"Success" : error));
if (error) {
onError(error);
}
}];
}
+(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName
{
#if 0
NSString * identifier = [[NSUserDefaults standardUserDefaults]objectForKey:kAlbumIdentifier];
if (!identifier) return nil;
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[identifier]
options:nil];
#else
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAlbumRegular
options:nil];
#endif
NSLog(@"assetCollections.count = %lu", assetCollections.count);
if (assetCollections.count == 0) return nil;
__block PHAssetCollection * myAlbum;
[assetCollections enumerateObjectsUsingBlock:^(PHAssetCollection *album, NSUInteger idx, BOOL *stop) {
NSLog(@"album:%@", album);
NSLog(@"album.localizedTitle:%@", album.localizedTitle);
if ([album.localizedTitle isEqualToString:AlbumName]) {
myAlbum = album;
*stop = YES;
}
}];
if (!myAlbum) return nil;
return myAlbum;
}
+(NSArray *)getAssets:(PHFetchResult *)fetch
{
__block NSMutableArray * assetArray = NSMutableArray.new;
[fetch enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
NSLog(@"asset:%@", asset);
[assetArray addObject:asset];
}];
return assetArray;
}
+ (void)getImageWithIdentifier:(NSString*)imageId onSuccess:(void(^)(UIImage *image))onSuccess onError: (void(^)(NSError * error)) onError
{
NSError *error = [[NSError alloc] init];
PHFetchResult *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[imageId] options:nil];
if (assets.count == 0) onError(error);
NSArray * assetArray = [self getAssets:assets];
PHImageManager *manager = [PHImageManager defaultManager];
CGRect screenRect = [[UIScreen mainScreen] bounds];
[manager requestImageForAsset:assetArray.firstObject targetSize:screenRect.size contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
onSuccess(result);
}];
}
@end
然后使用此方法点击图片按钮创建自定义相册并将图像保存在该自定义相册中。
// Take Image Button Method
- (void)snapButtonPressed:(UIButton *)button
{
[self.camera capture:^(LLSimpleCamera *camera, UIImage *image,
NSDictionary *metadata, NSError *error)
{
if(!error)
{
NSString * info = [NSString stringWithFormat:@"Size: %@ - Orientation: %ld", NSStringFromCGSize(image.size), (long)image.imageOrientation];
[CustomAlbum addNewAssetWithImage:image toAlbum:[CustomAlbum getMyAlbumWithName:CSAlbum] onSuccess:^(NSString *ImageId) {
NSLog(@"%@",ImageId);
recentImg = ImageId;
} onError:^(NSError *error) {
NSLog(@"probelm in saving image");
}];
}
else
{
NSLog(@"An error has occured: %@", error);
}
}
exactSeenImage:YES];
}
这是有效的代码。
__block PHAssetCollection *collection;
// Find the album
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", @"YOUR_CUSTOM_ALBUM_NAME"];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchOptions].firstObject;
PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
[collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//add assets to an array for later use in the uicollectionviewcell
}];
只需尝试一次此代码。您可以使用此代码将所有图像放在一个数组中:-
-(void)getAllPictures
{
__block PHAssetCollection *collection;
// Find the album
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", @"YOUR_CUSTOM_ALBUM_NAME"];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchOptions].firstObject;
PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
NSMutableArray *assets = [[NSMutableArray alloc] init];
[collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
[assets addObject:asset];
}];
PHImageRequestOptions * requestOptions = [[PHImageRequestOptions alloc] init];
//requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
//requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
//requestOptions.synchronous = true;
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[assets count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in assets) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize//CGSizeMake(300, 300)
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
NSLog(@"images %@", images); //You will get all images into this images array.
}
详情请参考Example app using Photos framework。
希望,这就是您要找的。有任何疑虑,请回复我。 :)