列举图片库中的所有图片

首先,将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

 

示例图:


猜你喜欢

转载自eric-gao.iteye.com/blog/1688700