iOS 獲取網(wǎng)絡(luò)視頻第一幀

現(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容