下载多个音频文件

时间:2016-05-17 15:05:00

标签: ios objective-c download download-manager nsurlsessiondownloadtask

我试图从服务器上下载多个.mp3文件。一个完整的音频文件分为286个部分。我获取文件的所有网址,现在我想下载286个文件。我搜索了很多,但是当我回到之前的控制器时,许多库停止下载,如果用户最小化应用程序,则下载停止。是否有任何库可以管理多个下载和下载当用户返回到最小化应用程序的前一个控制器时没有停止。 我正在使用下载管理器库,但我无法得到我想要的。请给我解决方案。我坚持了3天。请告诉我解决方案。感谢

1 个答案:

答案 0 :(得分: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];
}

希望它对你有所帮助。

相关问题