使用AssetsLibrary.Framework创建多图片选择控制器(翻译)

  系统的UIImagePickerController只能让用户选择单图片,而一般情况下,我们需要上传多张图片,这时应该可以同时选择多张图片,否则用户体验会很差。因此多图片选择器就诞生了。

  在类库中,苹果为我们提供了一个AssetsLibrary.Framework的库,可以通过它获取设备里的图片和视频。在使用这个类库时,我们需要导入,且<AssetsLibrary/AssetsLibrary.h>。然后我们可以使用它来获取不同组的枚举。

 1 void (^assetGroupEnumerator)
 2 (struct ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop{
 3   if(group != nil) {
 4     [assetGroups addObject:group];
 5     NSLog(@"Number of assets in group: %d",
 6                  [group numberOfAssets]);
 7   }
 8 };
 9 
10 assetGroups = [[NSMutableArray alloc] init];
11 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
12 NSUInteger groupTypes = ALAssetsGroupAll; 
13 
14 [library enumerateGroupsWithTypes:groupTypes
15     usingBlock:assetGroupEnumerator
16     failureBlock:^(NSError *error) {NSLog(@"A problem occurred");}];
17 
18 NSLog(@"Asset groups: %@", assetGroups);
19 [library release];

  1-8行,我们声明一个block,使用它来枚举所有asset group,然后将所有获取到的group放在NSMutableArray中。

 1 void (^assetEnumerator)
 2 (struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
 3   if(result != nil) {
 4     if(![assetURLDictionaries containsObject:[result valueForProperty:ALAssetPropertyURLs]]) {
 5       if(![[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {
 6         [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
 7         [assets addObject:result];
 8       }
 9     }
10   }
11 };
12 
13 assets = [[NSMutableArray alloc] init];
14 assetURLDictionaries = [[NSMutableArray alloc] init];
15 
16 NSInteger indexOfExampleGallery = NSNotFound;
17 for (ALAssetsGroup *group in assetGroups) {
18   if ([[group valueForProperty:ALAssetsGroupPropertyName]
19       isEqualToString:@"ExampleGallery"])
20   indexOfExampleGallery = [assetGroups indexOfObject:group];
21 }
22 
23 if (indexOfExampleGallery != NSNotFound) {
24   [[assetGroups objectAtIndex:indexOfExampleGallery]
25   enumerateAssetsUsingBlock:assetEnumerator];
26   NSLog(@"Assets %@", assets);
27 }
28 else
29   NSLog(@"Gallery 'ExampleGallery' not found on device.");

  代码中的ELCImagePickerController就是使用这个库来完成同时选择多张图片,当然视频也可以。

  ELCImagePickerController的使用

1     ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName:@"ELCAlbumPickerController" bundle:[NSBundle mainBundle]];    
2     ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
3     [albumController setParent:elcPicker];
4     [elcPicker setDelegate:self];
5     
6     ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
7     [app.viewController presentModalViewController:elcPicker animated:YES];

原文连接

posted @ 2012-12-23 21:06  ForrestWoo  阅读(5150)  评论(1编辑  收藏  举报