我试图一次从服务器下载多个.mp3文件。一个完整的音频文件分为286个部分。我获取了该文件的所有URL,现在我想下载286个文件。我搜索了很多,但当我回到以前的控制器时,许多库停止下载,如果用户最小化应用程序,则下载停止。是否有任何库可以管理多次下载,并且当用户返回到最小化应用程序的前一个控制器时,下载没有停止。我正在使用下载管理器库,但无法获得所需的。请给我解决方案。我从3天起就一直坚持着。请告诉我解决办法。感谢
在我的项目中,我使用的是AFNetwirking。您可以创建一个singleton对象,下面是我下载文件的方法(例如):
- (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];
}
希望它能帮助你。