使用AssetsLibrary框架在数组中获取iPhone照片库中的所有图片?

19

我想从照片库中获取所有的图片。我希望有一个可直接使用的方法或示例。


请尝试执行一次:https://dev59.com/kZffa4cB1Zd3GeqP6VQb#38992502 - Meet Doshi
3个回答

29

//视图控制器头文件(.h)...

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

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

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

 @end

//实现文件

将计数变量声明为全局变量

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

使用getAllPicture方法从照片库中获取照片。

或者您可以查看这篇博客http://mutiselectimagepicker.blogspot.in/2014/08/imageselect-to-allow-multiple-selection.html


1
以上方法的内存占用非常巨大!尽管这是一种非常恰当且简单的方法。由于使用异步块,内存管理在这种情况下变得特别困难。 - Ankit Malhotra
1
如果我们使用“#include <AssetsLibrary/AssetsLibrary.h>”,会出现错误。因此,请在您的头文件中使用以下内容以消除任何错误:#import <AssetsLibrary/ALAsset.h>获取帮助: http://stackoverflow.com/questions/10342931/alasset-valueforpropertyalassetpropertylocation-undeclared - Harjot Singh
导入 #import <AssetsLibrary/ALAssetRepresentation.h>为了解决这个错误: 实例消息的接收器类型“ALAssetRepresentation”是一个前向声明 - Harjot Singh
如果加载的图像超过60张,内存会增加到500MB。在iOS 9.1上测试过,使用iPhone 6S。将发布改进后的答案。 - C0mrade
1
现在它已经被弃用了....!!! 你能提供使用PHPhotoLibrary的方法吗...????? - Sneha
显示剩余4条评论

7

由于ALAssetsLibrary已经过时,现在有了新的Photo Framework。我使用Objective C编写了自己的函数来从相机胶卷中获取所有照片并存储在NSArray中,并在我的集合视图中显示。

 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
}

出现崩溃,类似于 [PHPhotoLibrary init[ 不受支持。 - Gowri G
有没有其他解决方案可以解决这个问题。请告诉我? - Gowri G

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

你可以使用以下方法在iOS中从资源库中获取所有图像或视频。 使用assetslibrary框架(必须) 注意:#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"];
            }
        }
    }];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接