首先,将AssetsLibrary.framework导入到项目中。
PhotosViewController.h
#import <UIKit/UIKit.h> #import <AssetsLibrary/AssetsLibrary.h> @interface PhotosViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{ NSMutableArray *assets; UITableView *tableView; UIActivityIndicatorView *activity; } @property (nonatomic, retain) IBOutlet UITableView *tableView; @property (nonatomic, retain) IBOutlet UIActivityIndicatorView *activity; @end
PhotosViewController.m
#import "PhotosViewController.h" @implementation PhotosViewController @synthesize tableView; @synthesize activity; - (void)dealloc { [tableView release]; [activity release]; [super dealloc]; } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) { if(result != NULL) { NSLog(@"See Asset: %@", result); [assets addObject:result]; } }; void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) { if(group != nil) { [group enumerateAssetsUsingBlock:assetEnumerator]; } [self.tableView reloadData]; [self.activity stopAnimating]; [self.activity setHidden:YES]; }; assets = [[NSMutableArray alloc] init]; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:assetGroupEnumerator failureBlock: ^(NSError *error) { NSLog(@"%@", error); }]; } - (void)viewDidUnload { [self setTableView:nil]; [self setActivity:nil]; [super viewDidUnload]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [assets count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } ALAsset *asset = [assets objectAtIndex:indexPath.row]; [cell.imageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]]; [cell.textLabel setText:[NSString stringWithFormat:@"Photo %d", indexPath.row+1]]; return cell; } @end
示例图: