获取视频PHAsset对象
PHFetchOptions *option = [[PHFetchOptions alloc] init];
option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeVideo];
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
//fetchAssetCollectionsWithType
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in smartAlbums) {
// 有可能是PHCollectionList类的的对象,过滤掉
if (![collection isKindOfClass:[PHAssetCollection class]]) continue;
// 过滤空相册
if (collection.estimatedAssetCount <= 0) continue;
if ([self isCameraRollAlbum:collection]) {
PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:option];
[fetchResult enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
PHAsset *phAsset = (PHAsset *)obj;
//可通过此PHAsset用下边方法分别获取时常、地址及缩略图
}];
}
}
//获取视频本地地址及时长
- (void)getVideoPathFromPHAsset:(PHAsset *)asset Complete:(void (^)(NSString *filePatch,NSString *dTime))result {
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHImageRequestOptionsVersionCurrent;
options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
NSString * sandboxExtensionTokenKey = info[@"PHImageFileSandboxExtensionTokenKey"];
NSArray * arr = [sandboxExtensionTokenKey componentsSeparatedByString:@";"];
NSString * filePath = arr[arr.count - 1];
CMTime time = [asset duration];
int seconds = ceil(time.value/time.timescale);
//format of minute
NSString *str_minute = [NSString stringWithFormat:@"%d",seconds/60];
//format of second
NSString *str_second = [NSString stringWithFormat:@"%.2d",seconds%60];
//format of time
NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
result(filePath,format_time);
}];
}
//获取视频缩略图
- (void)getVideoImageFromPHAsset:(PHAsset *)asset Complete:(void (^)(UIImage *image))resultBack{
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
option.resizeMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
UIImage *iamge = result;
resultBack(iamge);
}];
}
网友评论