19

I want to get all of the pictures from photoLibrary. I would prefer a method or example that I can use directly.

jonsca
  • 10,218
  • 26
  • 54
  • 62

3 Answers3

29

//View Controller header(.h) file..

#import <UIKit/UIKit.h>
#include <AssetsLibrary/AssetsLibrary.h> 

@interface getPhotoLibViewController : UIViewController
{
 ALAssetsLibrary *library;
 NSArray *imageArray;
 NSMutableArray *mutableArray;
}

-(void)allPhotosCollected:(NSArray*)imgArray;

 @end

//implementation file

declare global count variable as

static int count=0;

@implementation getPhotoLibViewController

-(void)getAllPictures
{
 imageArray=[[NSArray alloc] init];
 mutableArray =[[NSMutableArray alloc]init];
 NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];

 library = [[ALAssetsLibrary alloc] init];

 void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
  if(result != nil) {
   if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
    [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];

    NSURL *url= (NSURL*) [[result defaultRepresentation]url]; 

    [library assetForURL:url
             resultBlock:^(ALAsset *asset) {
              [mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];

              if ([mutableArray count]==count)
              {
               imageArray=[[NSArray alloc] initWithArray:mutableArray];
               [self allPhotosCollected:imageArray];
              }
             }
            failureBlock:^(NSError *error){ NSLog(@"operation was not successfull!"); } ]; 

   } 
  }
 };

 NSMutableArray *assetGroups = [[NSMutableArray alloc] init];

 void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
  if(group != nil) {
   [group enumerateAssetsUsingBlock:assetEnumerator];
   [assetGroups addObject:group];
   count=[group numberOfAssets];
  }
 };

 assetGroups = [[NSMutableArray alloc] init];

 [library enumerateGroupsWithTypes:ALAssetsGroupAll
                        usingBlock:assetGroupEnumerator
                      failureBlock:^(NSError *error) {NSLog(@"There is an error");}];
}

-(void)allPhotosCollected:(NSArray*)imgArray
{
 //write your code here after getting all the photos from library...
 NSLog(@"all pictures are %@",imgArray);
}

@end

Use getAllPicture method to get photos from photo library.

OR You can have a look at this blog http://mutiselectimagepicker.blogspot.in/2014/08/imageselect-to-allow-multiple-selection.html

Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
  • 1
    The memory footprint of above approach is tremendous ! Although it is a very apt & simple way of doing it. Memory management specifically becomes difficult in this due to use of asynchronous block. – Ankit Malhotra Feb 19 '14 at 01:02
  • 1
    It gives error, if we use "#include " So please use this in your header to remover any errors: #import For Help: http://stackoverflow.com/questions/10342931/alasset-valueforpropertyalassetpropertylocation-undeclared – Harjot Singh Mar 25 '14 at 05:54
  • Import #import For over come this error: Receiver type 'ALAssetRepresentation' for instance message is a forward declaration – Harjot Singh Mar 25 '14 at 06:59
  • If you load images more then 60, Memory goes up to 500MB. Tested on ios 9.1 with iphone 6S. will post improved answer. – C0mrade Nov 21 '15 at 16:09
  • For reducing memory consumption, you can get image thumbnails using [asset thumbnail] or [asset aspectRatioThumbnail] instead of [[asset defaultRepresentation] fullScreenImage]]. You can save image URLs and get full versions of images later on demand. – locomotion Nov 29 '15 at 11:03
  • to save memory save the ALAsset, then only fetch the image/thumbnail once you will dispaly it, or once the cell is being shown... – Underdog Dec 07 '15 at 04:42
  • AssetsLibrary is deprecated... Can we have new PHPhotoLibrary example. – karan Mar 02 '16 at 07:21
  • I added new version of getting photos, since AssetsLibrary was deprecated. – karan Mar 02 '16 at 09:10
  • 1
    its deprecated now .... !!! can you provide use of PHPhotoLibrary instead...????? – Sneha Aug 08 '16 at 10:13
7

Since ALAssetsLibrary is deprecated now and Photo Framework is new one. I made my own function in Objective C to get all photos from Camera Roll and store in NSArray and displayed in my Collectionview

 NSArray *imageArray;
 NSMutableArray *mutableArray;

-(void)getAllPhotosFromCamera
{
    imageArray=[[NSArray alloc] init];
    mutableArray =[[NSMutableArray alloc]init];

    PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
    requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    requestOptions.synchronous = true;
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];

    NSLog(@"%d",(int)result.count);

    PHImageManager *manager = [PHImageManager defaultManager];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];

    // assets contains PHAsset objects.

    __block UIImage *ima;
    for (PHAsset *asset in result) {
        // Do something with the asset

        [manager requestImageForAsset:asset
                           targetSize:PHImageManagerMaximumSize
                          contentMode:PHImageContentModeDefault
                              options:requestOptions
                        resultHandler:^void(UIImage *image, NSDictionary *info) {
                            ima = image;

                            [images addObject:ima];
                        }];


    }

    imageArray = [images copy];  // You can direct use NSMutuable Array images
}
karan
  • 3,319
  • 1
  • 35
  • 44
0

-(void)getFromGallery:(BOOL )IsImages
{
    if(self.csCollectionsArray != nil)
        [self.csCollectionsArray removeAllObjects];
    __block NSMutableDictionary *date = [[NSMutableDictionary alloc] init];
    ALAssetsLibrary *csAssetsLibrary = [[ALAssetsLibrary alloc] init];
    NSUInteger groupTypes = ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos;
    [csAssetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:^(ALAssetsGroup *group, BOOL *stop)
    {
        if([group numberOfAssets] > 0)
        {
            if(IsImages)
                [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            else
                [group setAssetsFilter:[ALAssetsFilter allVideos]];
            [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
            {
                if(asset)
                { //1.fetching all assets from device library
                    //2.Add all fetched assests from library
                    [date setObject:asset forKey:[asset valueForProperty:ALAssetPropertyDate]];
                }
            }];
        }
        else
        { NSLog(@"---> load table -------->");
            if(date != nil && date.count > 0)
            { //3.Sort using date by ascending order and moved to dictionary to array
                NSArray *sortedKeys = [[date allKeys] sortedArrayUsingSelector: @selector(compare:)];
                for (NSString *key in sortedKeys)
                    [self.csCollectionsArray addObject: [date objectForKey:key]];
                //4.Load images into collection view after fetching all datas
                [self reloadCollectionView];
                if(self.csCollectionView != nil)
                    [self.csCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:([self.csCollectionsArray count] - 1) inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
            }
            date = nil;
        }
    }failureBlock:^(NSError *error)
    {
        if((csCollectionsArray == nil || [csCollectionsArray count] == 0))
        {
            ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus]; if(status != ALAuthorizationStatusAuthorized)
            {
                [self showAlertAndCloseUploaderView:@"You can just go to \"Settings\" app (General -> Reset -> Reset Location & Privacy) then come again and click ok when the alert dialog is showing for enable the permission to access the photo library"];
            }
        }
    }];
}

You can use this below method to fetch all images or videos from assets library in ios. Use this assetslibrary framework(must) NOTE:- #import

-(void)getFromGallery:(BOOL )IsImages
{
    if(self.csCollectionsArray != nil)
        [self.csCollectionsArray removeAllObjects];
    __block NSMutableDictionary *date = [[NSMutableDictionary alloc] init];
    ALAssetsLibrary *csAssetsLibrary = [[ALAssetsLibrary alloc] init];
    NSUInteger groupTypes = ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos;
    [csAssetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:^(ALAssetsGroup *group, BOOL *stop)
    {
        if([group numberOfAssets] > 0)
        {
            if(IsImages)
                [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            else
                [group setAssetsFilter:[ALAssetsFilter allVideos]];
            [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
            {
                if(asset)
                { //1.fetching all assets from device library
                    //2.Add all fetched assests from library
                    [date setObject:asset forKey:[asset valueForProperty:ALAssetPropertyDate]];
                }
            }];
        }
        else
        { NSLog(@"---> load table -------->");
            if(date != nil && date.count > 0)
            { //3.Sort using date by ascending order and moved to dictionary to array
                NSArray *sortedKeys = [[date allKeys] sortedArrayUsingSelector: @selector(compare:)];
                for (NSString *key in sortedKeys)
                    [self.csCollectionsArray addObject: [date objectForKey:key]];
                //4.Load images into collection view after fetching all datas
                [self reloadCollectionView];
                if(self.csCollectionView != nil)
                    [self.csCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:([self.csCollectionsArray count] - 1) inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
            }
            date = nil;
        }
    }failureBlock:^(NSError *error)
    {
        if((csCollectionsArray == nil || [csCollectionsArray count] == 0))
        {
            ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus]; if(status != ALAuthorizationStatusAuthorized)
            {
                [self showAlertAndCloseUploaderView:@"You can just go to \"Settings\" app (General -> Reset -> Reset Location & Privacy) then come again and click ok when the alert dialog is showing for enable the permission to access the photo library"];
            }
        }
    }];
}
Robert
  • 5,278
  • 43
  • 65
  • 115
Kanagaraj
  • 51
  • 3