0

我試圖從服務器上下載多個.mp3文件。一個完整的音頻文件被分成286個部分。我獲取該文件的所有網址,現在我想下載286個文件。我搜索了很多,但當我回到前一個控制器時,如果用戶最小化應用程序下載的停止,許多庫停止下載。有什麼圖書館可以管理多個下載和下載沒有停止時,用戶回到前面的控制器最小化的應用程序。 我正在使用下載管理器庫,但我無法得到我想要的。請給我解決方案。我被困在那裏從3天。請告訴我解決方案。謝謝下載多個音頻文件

+0

嘗試AFNetworking iOS版 –

+0

您應該在NSURLSession中創建一個背景隊列 – Lefteris

回答

0

在我的項目中我使用AFNetwirking。您可以創建一個單獨的對象,這裏是我的下載文件的方法(例如):

- (AFHTTPRequestOperation *)performDownloadWithURLString:(nonnull NSString *)urlString 
            destinationPath:(NSString *)destinationPath 
              progress:(void (^)(long long bytesRead, long long totalBytesToRead))progress 
             apiCallback:(void(^)(BOOL isSuccessful, id object))apiCallback 
{ 

    NSURL *url = [NSURL URLWithString:urlString]; 

    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

    NSString *fullPath = [[FCFileManager pathForTemporaryDirectory] stringByAppendingPathComponent:[url lastPathComponent]]; 

    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]]; 

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) 
    { 
     if(progress) { 
      progress(totalBytesRead, totalBytesExpectedToRead); 
     } 
    }]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

      if(destinationPath && [FCFileManager isFileItemAtPath:destinationPath]) { 
       NSError *removeError; 
       [FCFileManager removeItemAtPath:destinationPath error:&removeError]; 
      } 
      if(destinationPath) { 
       [FCFileManager moveItemAtPath:fullPath toPath:destinationPath]; 
      } 

      dispatch_async(dispatch_get_main_queue(), ^{ 
       if(apiCallback) { 
        apiCallback(YES, destinationPath ?: fullPath); 
       } 
      }); 
     }); 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

     NSError *removeError; 
     [FCFileManager removeItemAtPath:fullPath error:&removeError]; 

     if(apiCallback) { 
      apiCallback(NO, [AZError errorWithNSError:error]); 
     } 

    }]; 
    [operation start]; 
} 

希望它可以幫助你。