現(xiàn)在的后臺(tái)越來(lái)越懶了,本來(lái)列表里面的圖片屬性應(yīng)該返回一個(gè)圖片的URL地址。
但是奇葩的后臺(tái)會(huì)返回兩種,一種是圖片鏈接,一種是視頻鏈接、如果是視頻的
話就需求自己取視頻的第一幀,而且還沒(méi)有字段判斷該鏈接是圖片鏈接還是視頻鏈接,這也難道不到咱。實(shí)現(xiàn)方法如下。
#import "VideoHelper.h"
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
#import <SDWebImage/SDImageCache.h>
@implementation VideoHelper
+(void)getVideoPreViewImageURL:(NSString *)videoURL forImageView:(BaseImageView *)imageView placeHolderImage:(UIImage *)placeHolder
{
[[SDImageCache sharedImageCache] queryCacheOperationForKey:videoURL done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
//是否有緩存圖片
if(image){
imageView.image = image;
}else{
//獲取視頻第一幀
[self getVideoFirstViewImage:videoURL forImageView:imageView placeHolderImage:placeHolder];
}
}];
}
// 獲取視頻第一幀
+ (void)getVideoFirstViewImage:(NSString *)videoURL forImageView:(BaseImageView *)imageView placeHolderImage:(UIImage *)placeHolder {
NSString *url = [NSString stringWithFormat:@"%@?flag=2",videoURL];
__block UIImage *videoImage;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:url] options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
NSError *thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(0, 60)actualTime:NULL error:&thumbnailImageGenerationError];
if(!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
videoImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef]: nil;
dispatch_async(dispatch_get_main_queue(), ^{
//主線程更新UI
if(videoImage){
imageView.image = videoImage;
//緩存圖片
[[SDImageCache sharedImageCache] storeImage:videoImage forKey:videoURL toDisk:NO completion:^{
}];
}else{
//如果不是視頻就設(shè)置圖片
[imageView setImageUrl:videoURL placeholderImage:placeHolder];
}
});
});
}
@end