I need to add group with name "MyGroupName" in ALAssetsLibrary . So I have used below code.
ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];
__weak ALAssetsLibrary *lib = library;
[library addAssetsGroupAlbumWithName:#"MyGroupName" resultBlock:^(ALAssetsGroup *group) {
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *g, BOOL *stop)
{
if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"MyGroupName"]) {
NSLog(#"group created with name 'MyGroupName'");
}
}failureBlock:^(NSError *error){
NSLog(#"failure %#",error);
}
];
} failureBlock:^(NSError *error) {
NSLog(#"failure %#",error);
}];
but inside "enumerateGroupsWithTypes" , group "g" is always nil in iOS 9.3.1 (iphone 6). its working correctly and group created with name "MyGroupName" on iOS 9.3.1 iphone 5. I want to know why above code is not working on iphone 6 and is there any solution to make it work ?
Please help me. Thanks in advance
1) First Import
#import <Photos/Photos.h>
#import <Photos/PHAsset.h>
#import <AssetsLibrary/AssetsLibrary.h>
2) Set property for ALAsset
#property (nonatomic, strong) ALAssetsLibrary* assetsLibrary;
3) Then allocate ALAsset library in your .m file
- (ALAssetsLibrary*)assetsLibrary
{
if (!_assetsLibrary) {
_assetsLibrary = [[ALAssetsLibrary alloc] init];
[ALAssetsLibrary disableSharedPhotoStreamsSupport];
}
return _assetsLibrary;
}
4 ) Now create method for save image to custom album
- (void)saveImageDatas:(UIImage*)imageDatas toAlbum:(NSString*)album withCompletionBlock:(void(^)(NSError *error))block
{
` if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSMutableArray* assets = [[NSMutableArray alloc]init];
PHAssetChangeRequest* assetRequest;
#autoreleasepool {
assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:imageDatas];
[assets addObject:assetRequest.placeholderForCreatedAsset];
}
__block PHAssetCollectionChangeRequest* assetCollectionRequest = nil;
PHFetchResult* result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
PHAssetCollection* collection = (PHAssetCollection*)obj;
if ([collection isKindOfClass:[PHAssetCollection class]]) {
if ([[collection localizedTitle] isEqualToString:album]) {
assetCollectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
[assetCollectionRequest addAssets:assets];
*stop = YES;
}
}
}];
if (assetCollectionRequest == nil) {
assetCollectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:album];
[assetCollectionRequest addAssets:assets];
}
}
completionHandler:^(BOOL success, NSError *error) {
if (block) {
block(error);
}
}];
}
else {
__weak ALAssetsLibrary* lib = [self assetsLibrary];
[[self assetsLibrary] writeImageDataToSavedPhotosAlbum:UIImageJPEGRepresentation(imageDatas, 1.0) metadata:nil completionBlock:^(NSURL* assetURL, NSError* error) {
if (error != nil) {
return;
}
__block BOOL albumWasFound = NO;
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup* group, BOOL* stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:album]) {
albumWasFound = YES;
[lib assetForURL:assetURL resultBlock:^(ALAsset* asset){
[group addAsset:asset];
if (block) {
block(nil);
}
}failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
return;
}
if (group == nil && albumWasFound == NO) {
[lib addAssetsGroupAlbumWithName:album resultBlock:^(ALAssetsGroup* group) {
} failureBlock:^(NSError* error) {
[lib assetForURL:assetURL resultBlock:^(ALAsset* asset){
[group addAsset:asset];
if (block) {
block(nil);
}
}failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
}];
}
} failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
}];
}
}
5 ) Now call this method to save the image like
[self saveImageDatas:myimage toAlbum:#"MyGroupName" withCompletionBlock:^(NSError *error) {
if (!error) {
NSLog(#"Sucess");
}
}];
"myimage" is your image that you want to save.
Please try this on:
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");
}];
Or Please check this link also
http://www.touch-code-magazine.com/ios5-saving-photos-in-custom-photo-album-category-for-download/
Related
I'm using Photos.Framework to save photos taken from the camera into my gallery and to retrieve them.
This is the code I'm using to store the photos:
__block PHAssetCollection *album = [self getMyAlbumWithName:#"MyAlbumName"];
if(album == nil)
{
[self makeAlbumWithTitle:#"MyAlbumName" onSuccess:^(NSString *AlbumId) {
album = [self getMyAlbumWithName:#"MyAlbumName"];
[self addNewAssetWithImage:_imageToStore toAlbum:album onSuccess:^(NSString *ImageId)
{
_imageLocalIdentifier = imageId;
} onError:^(NSError *error) {
// No need to do anything
}];
} onError:^(NSError *error) {
// No need to do anything
}];
}
else
{
[self addNewAssetWithImage:_imageToStore toAlbum:album onSuccess:^(NSString *ImageId)
{
_imageLocalIdentifier = imageId;
} onError:^(NSError *error) {
// No need to do anything
}];
}
-(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName
{
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAlbumRegular
options:nil];
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;
}
-(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);
}
}];
}
And this is the code I'm using to retrieve this photo:
PHImageManager *imgManager = [[PHImageManager alloc] init];
PHFetchResult* fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:#[_imageLocalIdentifier] options:nil];
if([fetchResult count] > 0)
{
PHAsset *asset = [fetchResult objectAtIndex:0];
PHImageRequestOptions *option = [PHImageRequestOptions new];
option.synchronous = NO;
option.version = PHImageRequestOptionsVersionCurrent;
option.networkAccessAllowed = YES;
option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
option.resizeMode = PHImageRequestOptionsResizeModeFast;
[imgManager requestImageForAsset:asset
targetSize:CGSizeMake(CAMERA_GALLERY_SIZE, CAMERA_GALLERY_SIZE)
contentMode:PHImageContentModeDefault
options:option
resultHandler:^(UIImage *result, NSDictionary *info) {
[cell.photoIV setImage:result];
}];
}
With this piece of code, over a sample of 12 photos stored (they are ok in my album) 4 or 5 of their localidentifiers returns an empty fetch results.
This is tested in iOS 8, iOS 9 and iOS 10 (with iOS 10 it's indeed worse because almost all of the fetch results are empty).
I've read that something similar to this was a bug in previous versions of iOS, but I guess this is not the reason now.
I've tried with this method to retrieve the photos:
- (PHAsset *)getAssetFromGallery:(NSString *)identifier
{
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:#[identifier] options:nil].lastObject;
if(asset != nil)
return asset;
__block PHAsset *result;
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
[fetchOptions setPredicate:[NSPredicate predicateWithFormat:#"localIdentifier == %#", identifier]];
[userAlbums enumerateObjectsUsingBlock:^(id _Nonnull objectCollection, NSUInteger idx, BOOL * _Nonnull stopCollectionEnumeration) {
PHAssetCollection *collection = nil;
if(![objectCollection isKindOfClass:[PHAssetCollection class]])
return;
collection = (PHAssetCollection *)objectCollection;
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
[assetsFetchResult enumerateObjectsUsingBlock:^(id _Nonnull objectAsset, NSUInteger idx, BOOL * _Nonnull stopAssetEnumeration) {
PHAsset *asset = nil;
if(![objectAsset isKindOfClass:[PHAsset class]])
return;
result = asset;
*stopAssetEnumeration = YES;
*stopCollectionEnumeration = YES;
}];
}];
return asset;
}
I've tried with PHAssetCollectionSubtypeAlbumMyPhotoStream instead of PHAssetCollectionSubtypeAny.
And I've tried with #"localIdentifier ==[cd] %#" instead of #"localIdentifier == %#".
And always the same results, lots of times the fetch results is empty.
Any idea of what is it happening?
My problem was that I wasn't saving the photos in the right way, I was calling onSuccess(placeHolder.localIdentifier); inside the performChanges block instead of inside the completionHandler block.
This is the code I'm using now to save the photos:
__block PHAssetCollection *album = [AuxiliaryFunctions getMyAlbumWithName:#"MyAlbumName" orWithIdentifier:#""];
if(album == nil)
[self makeAlbumWithTitle:#"MyAlbumName" onSuccess:^(NSString *AlbumId) {
album = [self getMyAlbumWithName:#"MyAlbumName" orWithIdentifier:AlbumId];
[self addNewAssetWithImage:_imageToStore toAlbum:album onSuccess:^(NSString *ImageId)
{
_imageLocalIdentifier = imageId;
} onError:^(NSError *error) {
// No need to do anything
}];
} onError:^(NSError *error) {
// No need to do anything
}];
else
{
[self addNewAssetWithImage:_imageToStore toAlbum:album onSuccess:^(NSString *ImageId)
{
_imageLocalIdentifier = imageId;
} onError:^(NSError *error) {
// No need to do anything
}];
}
-(PHAssetCollection *)getMyAlbumWithName:(NSString*)AlbumName orWithIdentifier:(NSString *)identifier
{
PHFetchResult *assetCollections = nil;
if(![identifier isEqualToString:#""])
{
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = [NSPredicate predicateWithFormat:#"localIdentifier = %# OR title = %#", identifier, AlbumName];
assetCollections = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:#[identifier]
options:options];
}
else
{
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = [NSPredicate predicateWithFormat:#"title = %#", AlbumName];
assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:options];
}
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;
}
-(void)makeAlbumWithTitle:(NSString *)title onSuccess:(void(^)(NSString *AlbumId))onSuccess onError: (void(^)(NSError * error)) onError
{
__block NSString *localIdentifier = #"";
//Check weather the album already exist or not
if (![self getMyAlbumWithName:title orWithIdentifier:#""])
{
[[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)
{
localIdentifier = placeHolder.localIdentifier;
// This line was the problem
//onSuccess(localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(#"Finished adding asset. %#", (success ? #"Success" : error));
if(success)
{
onSuccess(localIdentifier);
}
if (error)
{
onError(error);
}
}];
}
}
-(void)addNewAssetWithImage:(UIImage *)image
toAlbum:(PHAssetCollection *)album
onSuccess:(void(^)(NSString *ImageId))onSuccess
onError: (void(^)(NSError * error)) onError
{
__block NSString *localIdentifier = #"";
[[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) {
localIdentifier = placeHolder.localIdentifier;
// This line was the problem
//onSuccess(localIdentifier);
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(#"Finished adding asset. %#", (success ? #"Success" : error));
if(success)
{
onSuccess(localIdentifier);
}
if (error)
{
onError(error);
}
}];
}
I'm working on an iOS app in which I need gallery view like Instagram. I have added gallery View, camera View and video View, after taking image it saves to custom album of Photos. Now I want to retrieve those images from custom album and show it to Collection view of Gallery. But I'm getting stuck in retrieving those images from custom album. Any help will be appreciated.
Edit:
I added the PHPhotoLibrary for creating custom photo album, before this I added AssetsLibrary framework.
An Then I created a NSObject class (CustomAlbum) for creating and managing the custom photo album using 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
And then use this method on take Image Button click to create custom album and save images in that custom album.
// 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];
}
Here is the code that works.
__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
}];
Just try once this code.. You can get all images in one array using this code:-
-(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.
}
For more details, Please refer Example app using Photos framework.
Hope, this is what you're looking for. Any concern get back to me. :)
I want to fetch all the images from photo library I'm writing. Following code works on simulator but not on device. Please help me.Thanks in advance.
-(void)getImagesFromDevice
{
arrOfImages = [[NSMutableArray alloc]init];
if (_isForAvtars)
{
}
else
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];//ALAssetsGroupAll
NSLog(#"Authirization status:%ld",(long)[ALAssetsLibrary authorizationStatus]);
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
if (group != nil)
{
NSLog(#"Gruop is not nil");
NSLog(#"name %#",[group valueForProperty:ALAssetsGroupPropertyName]);
int a = (int)[group numberOfAssets];
NSLog(#"%d",a);
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if(result == nil)
{
return;
}
UIImage *img = [UIImage imageWithCGImage:[[result defaultRepresentation] fullScreenImage] scale:1.0 orientation:(UIImageOrientation)[[result valueForProperty:#"ALAssetPropertyOrientation"] intValue]];
if (img != nil)
{
NSLog(#"Add image");
[arrOfImages addObject:img];
}
}];
}
else
{
NSLog(#"Gruop is nil");
[collectionviewPhotosVideos reloadData];
}
}
failureBlock: ^(NSError *error)
{
NSLog(#"No groups");
}
];
}
I'm trying to save a photo taken with the camera to a custom photo album in iOS7.
my code looks like this:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
__block ALAssetsGroup* folder;
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"UrbanAlphabets"])
{
folder = group;
}
}
failureBlock:^(NSError* error)
{
// Error handling.
}];
[library writeImageToSavedPhotosAlbum:(__bridge CGImageRef)(image)
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error)
{
if (error.code == 0)
{
// Get the asset
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset)
{
// Assign the photo to the album
[folder addAsset:asset];
NSLog(#"success");
}
failureBlock:^(NSError* error)
{
// Error handling.
NSLog(#"error1");
}];
}
else
{
// Error handling.
NSLog(#"error");
}
}];
and actually the console logs "success", so I guess everything should be fine, but it doesn't put the photo into the folder... I pretty much copypasted the code from here
http://www.ggkf.com/iphone/save-a-photo-to-a-folder-in-photo-library
any ideas?
this made it work
//write to photo library
NSString *albumName=#"Urban Alphabets";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
__block ALAssetsGroup* groupToAddTo;
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:albumName]) {
groupToAddTo = group;
}
}
failureBlock:^(NSError* error) {
}];
CGImageRef img = [croppedImage CGImage];
[library writeImageToSavedPhotosAlbum:img
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
// try to get the asset
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
}];
}
else {
}
}];
All,
When the user of my app takes a photo, it will be saved but i want it to save in a new folder called 'Jasons Photos' and not the usual Camera Roll album.
I know of the completion block called save image:image toAlbum 'Jasons Album' with completion block, but I get an error complaining that 'No visible #interface for AlAssetslibrary declares the selector 'save image to album completion block' and its driving me crazy.
I have created an #property for the ALAssets library and i have included <AssetsLibrary> in my project.
thanks
You first need to write it to the savedPhotos, then get the ALAsset and add it to a new group
#import "QBViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#implementation QBViewController
- (void)viewDidLoad
{
[super viewDidLoad];
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib writeImageToSavedPhotosAlbum:[[UIImage imageNamed:#"polter"] CGImage] orientation:ALAssetOrientationUp completionBlock:^(NSURL *assetURL, NSError *error) {
if(assetURL) {
[lib assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[self addAsset:asset toGroup:#"forest" inLib:lib];
} failureBlock:^(NSError *error) {
NSLog(#"e: %#", error);
}];
}
else {
NSLog(#"e: %#", error);
}
}];
}
- (void) addAsset:(ALAsset*)a toGroup:(NSString*)name inLib:(ALAssetsLibrary*)lib {
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:name]) {
[group addAsset:a];
*stop = YES;
NSLog(#"added asset to EXISTING group");
}
if(!group) {
[lib addAssetsGroupAlbumWithName:name resultBlock:^(ALAssetsGroup *group) {
[group addAsset:a];
NSLog(#"added asset to NEW group");
} failureBlock:^(NSError *error) {
NSLog(#"e: %#", error);
}];
}
} failureBlock:^(NSError *error) {
NSLog(#"e: %#", error);
}];
}
#end