iOS多個視頻下載與停止下載的處理

視頻下載我使用的是

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    self.download = [self.urlSessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (progress && downloadProgress.finished) {
            progress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 這里要返回一個NSURL,其實就是文件的位置路徑
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 使用建議的路徑
        path = [path stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"》》》%@",path);
        // 轉(zhuǎn)化為文件路徑
        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (completion) {
            completion(filePath, error.localizedDescription);
        }
    }];
    [self.download resume];

此處self.urlSessionManager是AFURLSessionManager的對象

后臺傳的視頻地址是一個數(shù)組,所以我用了for循環(huán)來下載,開始時暫停下載里只寫了[self.download cancle],后來發(fā)現(xiàn)我暫停后下載任務還在執(zhí)行,仔細一想是因為for循環(huán)創(chuàng)建了多個下載隊列,我暫停的時候只是暫停了其中一個隊列,后來只能在網(wǎng)上查資料停止當前所有下載隊列的解決辦法。

// 取消當前所有的網(wǎng)絡請求
    NSMutableArray *taskData = [NSMutableArray arrayWithArray:[self.urlSessionManager downloadTasks]];
    [taskData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (((NSURLSessionDownloadTask *)obj).state != NSURLSessionTaskStateCompleted) {
            [(NSURLSessionDownloadTask *)obj cancel];
        }
    }];
    [taskData removeAllObjects];

后來又找到了這個方法,使用以后發(fā)現(xiàn)還是差點兒什么,于是我就在停止的地方加上了一個for循環(huán)并同步執(zhí)行,然后停止方法起了作用。

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

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

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