From 5f59ab83056d1ea85559603b62a816630c760482 Mon Sep 17 00:00:00 2001 From: eggmanQQQ <3671373519@qq.com> Date: Thu, 23 May 2024 17:21:40 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85=E8=B0=83=E6=95=B4=E5=90=8E?= =?UTF-8?q?=E7=9A=84=E7=BC=93=E5=AD=98=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../YMTabbar/View/TabbarViewController.m | 73 ++++------- YuMi/Tools/File/UploadFile.h | 10 +- YuMi/Tools/File/UploadFile.m | 124 ++++++++++++------ 3 files changed, 124 insertions(+), 83 deletions(-) diff --git a/YuMi/Modules/YMTabbar/View/TabbarViewController.m b/YuMi/Modules/YMTabbar/View/TabbarViewController.m index c454e4cb..13cc4d0c 100644 --- a/YuMi/Modules/YMTabbar/View/TabbarViewController.m +++ b/YuMi/Modules/YMTabbar/View/TabbarViewController.m @@ -121,8 +121,6 @@ UIKIT_EXTERN NSString *kTabShowAnchorCardKey; @property(nonatomic,assign) BOOL isReloadTicket; ///房间外的飘屏 @property(nonatomic,strong) PIFullScreenBannerAnimation *roomAnimation; -///缓存礼物的次数,超过了就不缓存了 -@property(nonatomic,assign) int downloadGiftCount; @end @@ -326,55 +324,42 @@ UIKIT_EXTERN NSString *kTabShowAnchorCardKey; } ///缓存礼物特效 -(void)requestGiftList{ - + [self removeOldVersionCacheFromOldMethod]; + @kWeakify(self); - [[AFNetworkReachabilityManager sharedManager] startMonitoring]; - [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + AFNetworkReachabilityManager *networkManager = [AFNetworkReachabilityManager sharedManager]; + [networkManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { @kStrongify(self); - switch (status) { - case AFNetworkReachabilityStatusUnknown: - break; - case AFNetworkReachabilityStatusNotReachable: - - break; - case AFNetworkReachabilityStatusReachableViaWWAN: - case AFNetworkReachabilityStatusReachableViaWiFi: - { - if(self.isFirstReachability == NO){ - - [self dealWithGiftList]; - [Api requestCacheGiftDynamicEffectList:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) { - if(code == 200){ - self.isFirstReachability = YES; - NSMutableArray *giftList = [[NSMutableArray alloc]initWithArray:data.data ?: @[]]; - NSArray *elfList = @[@"https://image.hfighting.com/fenjie2.mp4",@"https://image.hfighting.com/treasure_fairy_ten.mp4",@"https://image.hfighting.com/hecheng3.mp4",@"https://image.hfighting.com/treasure_fairy_one.mp4"]; - [giftList addObjectsFromArray:elfList]; - NSSet *setList = [[NSSet alloc]initWithArray:giftList];///去重,防止有重复的 - [self cacheGiftDynamicEffectList:setList]; + if (status == AFNetworkReachabilityStatusReachableViaWiFi) { + if(self.isFirstReachability == NO){ + [Api requestCacheGiftDynamicEffectList:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) { + if(code == 200){ + self.isFirstReachability = YES; + NSArray *allResourceList = data.data; + NSSet *allResourceSet = [[NSSet alloc] initWithArray:allResourceList]; + NSMutableArray *allResourceURLs = @[@"https://image.hfighting.com/fenjie2.mp4", + @"https://image.hfighting.com/treasure_fairy_ten.mp4", + @"https://image.hfighting.com/hecheng3.mp4", + @"https://image.hfighting.com/treasure_fairy_one.mp4"].mutableCopy; + for (NSString *url in allResourceSet) { + NSString *encodingUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet]; + [allResourceURLs addObject:encodingUrl]; } - }]; - } - + [[UploadFile share] startBatchDownloadWithURLs:allResourceURLs]; + } + }]; + } else { + [[UploadFile share] resumeBatchDownload]; } - break; - default: - break; + } else { + [[UploadFile share] pauseBatchDownload]; } }]; - - + [networkManager startMonitoring]; } - -///缓存新的礼物动效数据 --(void)cacheGiftDynamicEffectList:(NSSet *)list{ - [UploadFile downloadGiftDynamicEffectWithList:list completion:^(BOOL isSuccess, NSMutableArray * _Nonnull failList) { - - }]; -} - --(void)dealWithGiftList{ - ///删除旧数据缓存, +-(void)removeOldVersionCacheFromOldMethod{ + //MARK: 删除旧数据缓存,预计 2 个版本后可以删除此方法 NSString *svgaFileName = @"/GiftSvga"; NSString *svgaFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:svgaFileName]; if ([[NSFileManager defaultManager] fileExistsAtPath:svgaFilePath]) { @@ -382,7 +367,6 @@ UIKIT_EXTERN NSString *kTabShowAnchorCardKey; if(isSuccess == YES){ NSLog(@"删除成功"); } - } NSString *mp4FileName = @"/GiftMp4"; @@ -392,7 +376,6 @@ UIKIT_EXTERN NSString *kTabShowAnchorCardKey; if(isSuccess == YES){ NSLog(@"删除成功"); } - } } diff --git a/YuMi/Tools/File/UploadFile.h b/YuMi/Tools/File/UploadFile.h index 1a81c815..736fac35 100644 --- a/YuMi/Tools/File/UploadFile.h +++ b/YuMi/Tools/File/UploadFile.h @@ -37,9 +37,17 @@ NS_ASSUME_NONNULL_BEGIN failure:(void (^)(NSNumber *resCode, NSString *message))failure; ///下载资料 --(void)downloadAnimationFileName:(NSString *)fileName localPath:(NSString *)localPath completion:(void (^) (BOOL isSuccess, NSString *editAudioPath))completion; +- (void)downloadAnimationFileName:(NSString *)fileName localPath:(NSString *)localPath completion:(void (^) (BOOL isSuccess, NSString *editAudioPath))completion; + ///下载礼物特效 +(void)downloadGiftDynamicEffectWithList:(NSSet *)list completion:(void (^) (BOOL isSuccess, NSMutableArray *editAudioPath))completion; + + +// 批量下载 +- (void)startBatchDownloadWithURLs:(NSArray *)URLs; +- (void)pauseBatchDownload; +- (void)resumeBatchDownload; + @end NS_ASSUME_NONNULL_END diff --git a/YuMi/Tools/File/UploadFile.m b/YuMi/Tools/File/UploadFile.m index c72f519e..872636d7 100644 --- a/YuMi/Tools/File/UploadFile.m +++ b/YuMi/Tools/File/UploadFile.m @@ -15,6 +15,11 @@ static UploadFile* manager; // 一个脚手架实例 @property (nonatomic) QCloudCredentailFenceQueue* credentialFenceQueue; @property(nonatomic,strong) UploadFileModel *fileModel; + +// MARK: 批量下载部分, 后续要新建一个 object 来承载业务 +@property (nonatomic, strong) AFHTTPSessionManager *manager; +@property (nonatomic, strong) NSMutableArray *tasks; + @end @implementation UploadFile @@ -258,9 +263,12 @@ static UploadFile* manager; [[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request]; } -+(void)downloadAudioWithFileName:(NSString *)fileName musicUrl:(NSString *)musicUrl mainFileName:(NSString *)mainFileName completion:(void (^) (BOOL isSuccess, NSString *editAudioPath))completion { ++(void)downloadAudioWithFileName:(NSString *)fileName + musicUrl:(NSString *)musicUrl + mainFileName:(NSString *)mainFileName + completion:(void (^) (BOOL isSuccess, NSString *editAudioPath))completion { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; - NSURL *url = [NSURL URLWithString:[musicUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]; + NSURL *url = [NSURL URLWithString:[musicUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]; NSURLRequest *request = [NSURLRequest requestWithURL :url]; NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { @@ -276,49 +284,91 @@ static UploadFile* manager; [download resume]; } -+(void)downloadGiftDynamicEffectWithList:(NSSet *)list completion:(void (^) (BOOL isSuccess, NSMutableArray *editAudioPath))completion{ +// 批量下载 +- (void)startBatchDownloadWithURLs:(NSArray *)URLs { + if (_manager == nil) { + _manager = [AFHTTPSessionManager manager]; + _manager.operationQueue.maxConcurrentOperationCount = 10; + _tasks = [NSMutableArray array]; + } + + if (URLs.count == 0) { + return; + } - AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; - manager.operationQueue.maxConcurrentOperationCount = 10; // 控制并发数量 - dispatch_group_t requestGroup = dispatch_group_create(); - NSMutableArray *failList = [NSMutableArray array]; - for (NSString *giftUrl in list) { - NSString *encodingUrl = [giftUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet]; - NSString *fileName = [[encodingUrl componentsSeparatedByString:@"/"] lastObject]; - NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) safeObjectAtIndex1:0] stringByAppendingPathComponent:@"GiftDynamicEffectList"]; - NSString *fullPath = [filePath stringByAppendingPathComponent:fileName]; - if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { + [self createCacheLocalPath]; + + for (NSString *urlStr in URLs) { + // 缓存本地目标位置 + NSURL *destinationURL = [self localPath:urlStr]; + + // 检查文件是否已经存在 + if ([[NSFileManager defaultManager] fileExistsAtPath:[destinationURL path]]) { continue; } - NSFileManager *fileMgr = [[NSFileManager alloc] init]; - [fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; - dispatch_group_enter(requestGroup); - NSURL *url = [NSURL URLWithString:[encodingUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]; - NSURLRequest *request = [NSURLRequest requestWithURL :url]; - NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { - } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { - return [NSURL fileURLWithPath:fullPath]; + + NSURL *url = [NSURL URLWithString:urlStr]; + NSURLRequest *request = [NSURLRequest requestWithURL:url]; + + @kWeakify(self); + __block NSURLSessionDownloadTask *downloadTask; + downloadTask = [self.manager downloadTaskWithRequest:request + progress:nil + destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { + return destinationURL; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { - dispatch_group_leave(requestGroup); - if (!error) { - NSLog(@"下载完成"); - } else { - NSLog(@"下载失败"); - [failList addObject:encodingUrl]; + @kStrongify(self); + if ([self.tasks containsObject:downloadTask]) { + [self.tasks removeObject:downloadTask]; } }]; - [download resume]; + + [self.tasks addObject:downloadTask]; } - dispatch_group_notify(requestGroup, dispatch_get_main_queue(), ^{ - if(failList.count > 0){ - completion(NO,failList); - NSLog(@"下载有失败,失败数:%ld,成功数:%ld,总数:%ld",failList.count,list.count - failList.count,list.count); - }else{ - NSLog(@"下载全部完成,总数:%ld",list.count); - completion(NO,nil); + + [self resumeBatchDownload]; +} + +- (void)pauseBatchDownload { + for (NSURLSessionDownloadTask *task in self.tasks) { + if (task.state == NSURLSessionTaskStateRunning) { + [task suspend]; } - }); - + } +} + +- (void)resumeBatchDownload { + for (NSURLSessionDownloadTask *task in self.tasks) { + if (task.state == NSURLSessionTaskStateSuspended) { + [task resume]; + } + } +} + +- (void)createCacheLocalPath { + NSError *error = nil; + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSString *filePath = [self cacheFilePath]; + if ([fileManager fileExistsAtPath:filePath] == NO) { + NSFileManager *fileMgr = [[NSFileManager alloc] init]; + BOOL success = [fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]; + if (success) { + NSLog(@"Folder created successfully."); + } else { + NSLog(@"Could not create folder: %@", [error localizedDescription]); + } + } +} + +- (NSURL *)localPath:(NSString *)encodingUrl { + NSString *fileName = [[encodingUrl componentsSeparatedByString:@"/"] lastObject]; + NSString *filePath = [self cacheFilePath]; + NSString *cacheLocalPath = [filePath stringByAppendingPathComponent:fileName]; + return [NSURL fileURLWithPath:cacheLocalPath]; +} + +- (NSString *)cacheFilePath { + return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) safeObjectAtIndex1:0] stringByAppendingPathComponent:@"GiftDynamicEffectList"]; } @end