使用AFNetworking 3.0,如何按顺序下载一系列文件?

时间:2016-01-02 22:31:45

标签: ios objective-c afnetworking nsurlsessiondownloadtask

所以,我已经在这些论坛和其他网站上搜索了几天,并且无法找到合适的替代方式来下载AFNetworking 1.0和2.0中的一系列文件。

我正在尝试使用NSURLSessionDownloadTask下载这些文件,但我知道它们不像线程,所以你不能这样处理它们。

以前我可以按顺序下载多个文件并获得总操作的进度更新(不仅是在每个文件上,而且在整个队列上)。

这是我使用的基本结构...

 for(Photo *photo in array){

    //form the path where you want to save your downloaded image to
    NSString *constPath = [photo imageFullPath];

    //url of your photo
    NSURL *url = [NSURL URLWithString:photo.serverPath];

    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
    op.responseSerializer = [AFImageResponseSerializer serializer];

    op.outputStream = [NSOutputStream outputStreamToFileAtPath:constPath append:NO];
    op.queuePriority = NSOperationQueuePriorityLow;
    [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){

    }];

    op.completionBlock = ^{

        //do whatever you want with the downloaded photo, it is stored in the path you create in constPath
    };
    [requestArray addObject:op];
}

NSArray *batches = [AFURLConnectionOperation batchOfRequestOperations:requestArray progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
} completionBlock:^(NSArray *operations) {

    //after all operations are completed this block is called
    if (successBlock)
        successBlock();
}];

[[NSOperationQueue mainQueue] addOperations:batches waitUntilFinished:NO];


(this code was taken from another post but it is exactly what i was using on a previous app)


And now, trying to use NSURLSessionDownloadTask, I can not find a way to adapt the following code to run in a series (1 file at a time, in order, with progress and file data along the way).

    NSURLSessionDownloadTask *newTask = [_downloadReqOps downloadTaskWithRequest:myRequest progress:^(NSProgress * _Nonnull downloadProgress) {

    //Progress 

        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

            NSString *filePath = [NSString stringWithFormat:@"%@/%@", [CompanyInfo storeFileInFolder:kTempFiles], response.URL.absoluteString.lastPathComponent];
            //NSLog(@"File Path: %@", filePath);//response.URL.absoluteString.lastPathComponent);

            return [NSURL fileURLWithPath:filePath];

        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

        }];

        [newTask resume];

我认为这曾经被称为AFNetworking 1.0中的“批处理”请求,但我知道这已经不再使用了。我正在尝试调整新的NSURLSessions来下载这些文件。

任何帮助将不胜感激!

0 个答案:

没有答案