iOS-使用ALAssetsLibrary获取相册图片视频

时间:2023-01-12 08:46:06

 

用ALAssetsLibrary获取相册图片视频

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:
^(ALAssetsGroup *group, BOOL *stop) {

// Filter down to only photos
[group setAssetsFilter:[ALAssetsFilter allPhotos]];

// Grab the first photo return
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:0]
options:
0
usingBlock:
^(ALAsset *result, NSUInteger index, BOOL *stop) {

if (result) {

id repressentation = [result defaultRepresentation];

// 可以生产一个AVAsset
NSURL *url = [repressentation url];
AVAsset
*asset = [AVAsset assetWithURL:url];

// 也可以直接获取image
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithCGImage:[repressentation fullResolutionImage]]];

}
}];
} failureBlock:
^(NSError *error) {

NSLog(
@"Error: %@", [error localizedDescription]);
}];

 

使用AVAsset加载资源:

    NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"guitar" withExtension:@"caf"];

AVAsset
*asset = [AVAsset assetWithURL:assetURL];

NSArray
*keys = @[@"tracks"];

[asset loadValuesAsynchronouslyForKeys:keys completionHandler:
^{

NSError
*error = nil;

AVKeyValueStatus status
= [asset statusOfValueForKey:@"tracks" error:&error];

switch (status) {
case AVKeyValueStatusLoaded:
// 加载完资源 to do
NSLog(@"加载完");
break;

case AVKeyValueStatusFailed:
// 加载失败 to do
NSLog(@"加载失败");
break;

case AVKeyValueStatusCancelled:
// 加载取消 to do
NSLog(@"加载取消");
break;

default:
break;
}
}];

 

获得元数据

    NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"123" withExtension:@"m4a"];

AVAsset
*asset = [AVAsset assetWithURL:assetURL];

NSArray
*keys = @[@"availableMetadataFormats"];

[asset loadValuesAsynchronouslyForKeys:keys completionHandler:
^{

NSMutableArray
*metadata = [NSMutableArray array];
for (NSString *format in asset.availableMetadataFormats) {

[metadata addObjectsFromArray:[asset metadataForFormat:format]];
}

NSLog(
@"meta format: %@", metadata);

NSString
*keySpace = AVMetadataKeySpaceiTunes;
NSString
*artistKey = AVMetadataiTunesMetadataKeyArtist;
NSString
*albumKey = AVMetadataiTunesMetadataKeyAlbum;

NSArray
*artistMetadata = [AVMetadataItem metadataItemsFromArray:metadata
withKey:artistKey
keySpace:keySpace];

NSArray
*albumMetadata = [AVMetadataItem metadataItemsFromArray:metadata
withKey:albumKey
keySpace:keySpace];

AVMetadataItem
*artistItem, *albumItem;
if (artistMetadata.count > 0) {
artistItem
= artistMetadata[0];
}

if (albumMetadata.count > 0) {
albumItem
= albumMetadata[0];
}
}];

 

使用AVMetadataItem

NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"123" withExtension:@"m4a"];

AVAsset
*asset = [AVAsset assetWithURL:assetURL];

NSArray
*metadata = [asset metadataForFormat:AVMetadataFormatiTunesMetadata];

for (AVMetadataItem *item in metadata) {

NSLog(
@"%@: %@", item.key, item.value);
}