如何从照片库中检索数组中的所有照片和视频?

问题描述:

在我的代码中,我尝试从照片库中获取所有照片并将它们存储在一个数组中。 我也想获取视频,并将它们存储在同一个数组中。 请告诉我如何根据上述要求修改此代码。 因为我是一个新手,我一直在努力争取这个。如何从照片库中检索数组中的所有照片和视频?

-(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); 
} 
+0

这有什么用'xcode'或' xcode 5'这些标签被保留用于'xcode IDE'本身的问题本身并不仅仅因为您正在使用该标签'xcode IDE'请参阅wiki http://*.com/tags/xcode/info – Popeye

你必须使用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]; 
} 

此代码会给你的iPhone视频列表。

它可以帮助你:)

For Future Reference Use this:-

+1

是的我已经使用了ALAssetsLibrary,我认为你提供的代码只会获取我的视频而不是照片。 – vanya

+0

@vanya更新了答案,看看! – Vizllx

+1

当你基本上把所有的照片(全分辨率)作为一个uiimage数组放入内存时,你是否担心内存使用?我问的原因是我试图保存获取返回的ALAsset,并且只在显示collectionViewCell(缩略图)时以及用户决定选择特定照片(用于完整分辨率)时才加载uiimage(lazily)。 – Ben

试试这个答案很简单,易于理解

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