Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/101.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何从照片库中检索阵列中的所有照片和视频?_Ios_Iphone_Objective C_Alassetslibrary - Fatal编程技术网

Ios 如何从照片库中检索阵列中的所有照片和视频?

Ios 如何从照片库中检索阵列中的所有照片和视频?,ios,iphone,objective-c,alassetslibrary,Ios,Iphone,Objective C,Alassetslibrary,在我的代码中,我尝试从照片库中获取所有照片并将它们存储在一个数组中。 我还想获取视频,并将它们存储在同一阵列中。 请告诉我如何根据上述要求修改此代码。 作为一名新手,我已经为此奋斗了几个月 -(IBAction)getAllPictures: (id) sender { imageArray=[[NSArray alloc] init]; mutableArray =[[NSMutableArray alloc]init]; NSMutableArray* assetUR

在我的代码中,我尝试从照片库中获取所有照片并将它们存储在一个数组中。 我还想获取视频,并将它们存储在同一阵列中。 请告诉我如何根据上述要求修改此代码。 作为一名新手,我已经为此奋斗了几个月

-(IBAction)getAllPictures: (id) sender
{
    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])
            {
                if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
                {

                  if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeUnknown])
                  {
                    [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);
}

您必须使用assetLibraries尝试以下代码:-

从照片库中获取所有照片的代码

- (void)viewDidLoad
{
    carousel.type = iCarouselTypeCoverFlow2;
    [super viewDidLoad];
    xy =[[NSMutableArray alloc]init];

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

    ALAssetsLibrary *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]];

                NSLog(@"result is:%@",result);
                NSLog(@"asset URLDictionary is:%@",assetURLDictionaries);
                NSURL *url= (NSURL*) [[result defaultRepresentation]url]; 

                [library assetForURL:url
                         resultBlock:^(ALAsset *asset) {
                             [xy addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
                             NSLog(@" xy is:%@",xy);
                             image =[ [UIImageView alloc ] initWithImage:[xy objectAtIndex:0]];
                             NSLog(@"image is:%@",image);
                         }
                         failureBlock:^(NSError *error){ NSLog(@"test:Fail"); } ]; 
            } 
        }
    };

    NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
    void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
        NSLog(@"hello");
        if(group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
            [assetGroups addObject:group];
            NSLog(@"Number of assets in group :%d",[group numberOfAssets]);
            NSLog(@"asset group is:%@",assetGroups);
        }
    };

    assetGroups = [[NSMutableArray alloc] init];

    [library enumerateGroupsWithTypes:ALAssetsGroupAll
             usingBlock:assetGroupEnumerator
             failureBlock:^(NSError *error) {NSLog(@"A problem occurred");}];
}
- (void)updateAssetsLibrary
{
loadImgView.hidden = NO;
[spinner startAnimating];
//selectVideoBtn .userInteractionEnabled = NO;

assetItems = [NSMutableArray arrayWithCapacity:0];
ALAssetsLibrary *assetLibrary = assetsLibrary;

[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) 
{
    if (group)
    {
        [group setAssetsFilter:[ALAssetsFilter allVideos]];
        [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
        {
             if (asset)
             {
                 dic = [[NSMutableDictionary alloc] init];
                 ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
                 NSString *uti = [defaultRepresentation UTI];
                 appDelegate.videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];

                 mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:appDelegate.videoURL];

                 NSString *title = [NSString stringWithFormat:@"%@ %i", NSLocalizedString(@"Video", nil), [assetItems count]+1];

                 [self performSelector:@selector(imageFromVideoURL)];
                 [dic setValue:title forKey:kName];
                 [dic setValue:appDelegate.videoURL forKey:kURL];

                 AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:appDelegate.videoURL title:title];
                 [assetItems addObject:item];
                 [appDelegate.videoURLArray addObject:dic];

                 NSLog(@"Video has info:%@",appDelegate.videoURLArray);
             }
             NSLog(@"Values of dictionary==>%@", dic);

             //NSLog(@"assetItems:%@",assetItems);
             NSLog(@"Videos Are:%@",appDelegate.videoURLArray);
        } ];
    }
    // group == nil signals we are done iterating.
    else 
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self updateBrowserItemsAndSignalDelegate:assetItems];
            loadImgView.hidden = NO;
            [spinner stopAnimating];
            [loadImgView removeFromSuperview];
            //selectVideoBtn .userInteractionEnabled = YES;
        });
    }
}
failureBlock:^(NSError *error) 
{
    NSLog(@"error enumerating AssetLibrary groups %@\n", error);
}];
}

- (UIImage *)imageFromVideoURL 
{
// result 
UIImage *image = nil;

// AVAssetImageGenerator
AVAsset *asset = [[AVURLAsset alloc] initWithURL:appDelegate.videoURL options:nil];; 
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;

// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600); 

// get the image from 
NSError *error = nil; 
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

if (halfWayImage != NULL) 
{
    // CGImage to UIImage
    image = [[UIImage alloc] initWithCGImage:halfWayImage];
    [dic setValue:image forKey:kImage];
    NSLog(@"Values of dictionary==>%@", dic);
    NSLog(@"Videos Are:%@",appDelegate.videoURLArray);
    CGImageRelease(halfWayImage);
}
return image;
}

- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
[self updateAssetsLibrary];
}

- (void)buildAssetsLibrary
{
assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;

NSString *minimumSystemVersion = @"4.1";
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
    notificationSender = assetsLibrary;

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetsLibraryDidChange:) name:ALAssetsLibraryChangedNotification object:notificationSender];
[self updateAssetsLibrary];
}
从库中获取所有视频的我的代码

- (void)viewDidLoad
{
    carousel.type = iCarouselTypeCoverFlow2;
    [super viewDidLoad];
    xy =[[NSMutableArray alloc]init];

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

    ALAssetsLibrary *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]];

                NSLog(@"result is:%@",result);
                NSLog(@"asset URLDictionary is:%@",assetURLDictionaries);
                NSURL *url= (NSURL*) [[result defaultRepresentation]url]; 

                [library assetForURL:url
                         resultBlock:^(ALAsset *asset) {
                             [xy addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
                             NSLog(@" xy is:%@",xy);
                             image =[ [UIImageView alloc ] initWithImage:[xy objectAtIndex:0]];
                             NSLog(@"image is:%@",image);
                         }
                         failureBlock:^(NSError *error){ NSLog(@"test:Fail"); } ]; 
            } 
        }
    };

    NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
    void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
        NSLog(@"hello");
        if(group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
            [assetGroups addObject:group];
            NSLog(@"Number of assets in group :%d",[group numberOfAssets]);
            NSLog(@"asset group is:%@",assetGroups);
        }
    };

    assetGroups = [[NSMutableArray alloc] init];

    [library enumerateGroupsWithTypes:ALAssetsGroupAll
             usingBlock:assetGroupEnumerator
             failureBlock:^(NSError *error) {NSLog(@"A problem occurred");}];
}
- (void)updateAssetsLibrary
{
loadImgView.hidden = NO;
[spinner startAnimating];
//selectVideoBtn .userInteractionEnabled = NO;

assetItems = [NSMutableArray arrayWithCapacity:0];
ALAssetsLibrary *assetLibrary = assetsLibrary;

[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) 
{
    if (group)
    {
        [group setAssetsFilter:[ALAssetsFilter allVideos]];
        [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
        {
             if (asset)
             {
                 dic = [[NSMutableDictionary alloc] init];
                 ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
                 NSString *uti = [defaultRepresentation UTI];
                 appDelegate.videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];

                 mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:appDelegate.videoURL];

                 NSString *title = [NSString stringWithFormat:@"%@ %i", NSLocalizedString(@"Video", nil), [assetItems count]+1];

                 [self performSelector:@selector(imageFromVideoURL)];
                 [dic setValue:title forKey:kName];
                 [dic setValue:appDelegate.videoURL forKey:kURL];

                 AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:appDelegate.videoURL title:title];
                 [assetItems addObject:item];
                 [appDelegate.videoURLArray addObject:dic];

                 NSLog(@"Video has info:%@",appDelegate.videoURLArray);
             }
             NSLog(@"Values of dictionary==>%@", dic);

             //NSLog(@"assetItems:%@",assetItems);
             NSLog(@"Videos Are:%@",appDelegate.videoURLArray);
        } ];
    }
    // group == nil signals we are done iterating.
    else 
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self updateBrowserItemsAndSignalDelegate:assetItems];
            loadImgView.hidden = NO;
            [spinner stopAnimating];
            [loadImgView removeFromSuperview];
            //selectVideoBtn .userInteractionEnabled = YES;
        });
    }
}
failureBlock:^(NSError *error) 
{
    NSLog(@"error enumerating AssetLibrary groups %@\n", error);
}];
}

- (UIImage *)imageFromVideoURL 
{
// result 
UIImage *image = nil;

// AVAssetImageGenerator
AVAsset *asset = [[AVURLAsset alloc] initWithURL:appDelegate.videoURL options:nil];; 
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;

// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600); 

// get the image from 
NSError *error = nil; 
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

if (halfWayImage != NULL) 
{
    // CGImage to UIImage
    image = [[UIImage alloc] initWithCGImage:halfWayImage];
    [dic setValue:image forKey:kImage];
    NSLog(@"Values of dictionary==>%@", dic);
    NSLog(@"Videos Are:%@",appDelegate.videoURLArray);
    CGImageRelease(halfWayImage);
}
return image;
}

- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
[self updateAssetsLibrary];
}

- (void)buildAssetsLibrary
{
assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;

NSString *minimumSystemVersion = @"4.1";
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
    notificationSender = assetsLibrary;

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetsLibraryDidChange:) name:ALAssetsLibraryChangedNotification object:notificationSender];
[self updateAssetsLibrary];
}
此代码将为您提供iPhone的视频列表

它可能会帮助你:)


试试这个简单易懂的答案

-(void)getFromGallery:(BOOL)iImage
{
if(self.csCollectionsArray!=nil)
[self.csCollectionsArray removeAllObjects];
__块NSMutableDictionary*date=[[NSMutableDictionary alloc]init];
AlassetLibrary*CsassetLibrary=[[AlassetLibrary alloc]init];
NSUInteger groupTypes=alassetGroupAlbum | alassetGroupEvent | alassetGroupFaces | alassetGroupSavedPhotos;
[csAssetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:^(ALASSETGROUP*group,BOOL*stop)
{
如果([group numberOfAssets]>0)
{
如果(IsImages)
[group SetAssetFilter:[AlasSetFilter allPhotos]];
其他的
[group SetAssetFilter:[AlasSetFilter allVideos]];
[组enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset*资产,NSU整数索引,布尔*停止)
{
如果(资产)
{//1.正在从设备库获取所有资产
//2.添加从库中提取的所有资产
[date setObject:asset forKey:[asset valueForProperty:ALAssetPropertyDate];
}
}];
}
其他的
{NSLog(@“--->加载表-------->”);
如果(日期!=nil&&date.count>0)
{//3.使用日期按升序排序,并移动到字典以进行数组排序
NSArray*sortedKeys=[[date allKeys]SortedArray使用选择器:@selector(比较:)];
用于(NSString*输入已分类密钥)
[self.csCollectionsArray addObject:[date objectForKey:key]];
//4.获取所有数据后将图像加载到采集视图中
[self-reloadCollectionView];
if(self.csCollectionView!=nil)
[self.csCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:([self.csCollectionsArray count]-1)安全设置:0]atScrollPosition:UICollectionViewScrollPositionBottom动画:是];
}
日期=零;
}
}故障块:^(N错误*错误)
{
如果((csCollectionsArray==nil | |[csCollectionsArray计数]==0))
{
AlaAuthorizationStatus=[ALAssetsLibrary authorizationStatus];如果(状态!=AlaAuthorizationStatusAuthorized)
{
[self-showAlertAndCloseUploaderView:@“您只需进入\“设置\”应用程序(常规->重置->重置位置和隐私),然后在显示“启用访问照片库的权限”的警报对话框时再次过来并单击“确定”];
}
}
}];

}
是的,我使用了AlassetLibrary,我认为您提供的代码只能为我获取视频,而不能获取照片。@vanya更新了答案,请查看!当您将所有照片(全分辨率)作为uiimage数组放入内存时,您是否担心内存使用问题?我问的原因是,我试图保存返回的阿拉斯集,并且仅在显示collectionViewCell(用于缩略图)和用户决定选择特定照片(用于全分辨率)时(延迟)加载uiimage。我建议只存储阿拉斯集数组,然后延迟加载。ALAssset有一个缩略图属性,它返回大约150x150的缩略图大小的图像,这对于大多数视图都非常有用。这种延迟加载速度很快,在我的视图中看不到任何减速或延迟。一个重要的注意事项是,如果您存储的是ALAsset,则它们仅在您从中获取它们的ALAssetLibrary的生命周期内有效,这与
xcode
xcode 5
无关。这些标记是为
xcode IDE
本身的问题保留的。不要仅仅因为使用
xcode IDE
就使用标记。请参见wiki