方法一:
- (void)loadAssets {
// Runin the background as it takes a while to get all assets from the library
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
NSMutableArray *assetURLDictionaries = [[NSMutableArray alloc] init];
//Process assets
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result != nil) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSString *assetType = [result valueForProperty:ALAssetPropertyType];
if ([assetType isEqualToString:ALAssetTypePhoto]) {
// photo
NSURL *url = result.defaultRepresentation.url;
[_assetLibrary assetForURL:url
resultBlock:^(ALAsset *asset) {
if (asset) {
@synchronized(_photoAssets) {
[_photoAssets addObject:asset];
}
}
}
failureBlock:^(NSError *error){
NSLog(@"operation was notsuccessfull!");
}];
}
else if ([assetType isEqualToString:ALAssetTypeVideo]) {
// video
NSURL *url = result.defaultRepresentation.url;
[_assetLibrary assetForURL:url
resultBlock:^(ALAsset *asset) {
if (asset) {
@synchronized(_videoAssets) {
[_videoAssets addObject:asset];
}
}
}
failureBlock:^(NSError *error){
NSLog(@"operation was not successfull!");
}];
}
else if ([assetType isEqualToString:ALAssetTypeUnknown]) {
// unknown
}
}
};
//Process groups
void (^ assetGroupEnumerator) (ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if (group != nil) {
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:assetEnumerator];
[assetGroups addObject:group];
}
else {
// 上传完
[self getPhotoAsset];
// [self getVideoAsset];
}
};
// Process!
[self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError*error) {
NSLog(@"There is an error");
}];
});
}
方法二:
- (void)cameraRollButtonPressed
{
NSMutableArray *datasource = [[NSMutableArray alloc] init];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
Photo *photo = [[Photo alloc] init];
photo.thumbnail = [UIImage imageWithCGImage:result.thumbnail];
photo.date = [result valueForProperty:ALAssetPropertyDate];
[datasource addObject:photo];
NSLog(@"%i", [datasource count]);
}
}];
} else {
[self performSelectorOnMainThread:@selector(showPhotoCollectionController:) withObject:datasource waitUntilDone:NO];
}
} failureBlock:^(NSError *error) {
NSLog(@"Failed.");
}];
}