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]; 
} 

希望它可以帮助你。