ios - 多个文件下载有问题

标签 ios nsurlsession nsurlsessiondownloadtask nsurlsessionconfiguration

目前我正在实现一个文件下载应用程序。 在我的应用服务器中有大约 2500 个资源文件,我需要将这些文件从服务器下载到我的文档目录。

我的代码:

@implementation DownloadManager
{
    NSURLSession *session;
    BOOL downloading;
}

#pragma mark - NSURLSessionDownloadDelegate

// Handle download completion from the task
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSInteger index = [self assetDownloadIndexForDownloadTask:downloadTask];
    if (index < 0)
    {
        return;
    }
    DownloadHelper *movieDownload = _assetsToDownload[index];

    // Copy temporary file
    NSError * error;
    [[NSFileManager defaultManager] copyItemAtURL:location toURL:[NSURL fileURLWithPath:[movieDownload localPath]] error:&error];
    downloading = NO;
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    // Required delegate method
}

// Handle task completion
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error)
        NSLog(@"Task %@ failed: %@", task, error);
    NSLog(@"Task %@ Success: %@", task, error);
    if ([_assetsToDownload count])
    {
        [_assetsToDownload removeObjectAtIndex:0];
    }

    downloading = NO;
    if ([_assetsToDownload count])
    {
        [self downloadFiles];
    }
    else
    {
        [self downloadAssets];
    }
}

// Handle progress update from the task
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSInteger index = [self assetDownloadIndexForDownloadTask:downloadTask];
    if (index < 0) return;
   // DownloadHelper *movieDownload = _assetsToDownload[index];
    double progress = (double) (totalBytesWritten/1024) / (double) (totalBytesExpectedToWrite/1024);
    dispatch_async(dispatch_get_main_queue(), ^{
        // Showing progress
    });

}

#pragma mark - Movie Download Handling & UI

// Helper method to get the index of a Asset from the array based on downloadTask.
- (NSInteger)assetDownloadIndexForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{
    NSInteger foundIndex = -1;
    NSInteger index = 0;
    for (DownloadHelper *asset in _assetsToDownload)
    {
        if (asset.downloadTask == downloadTask)
        {
            foundIndex = index;
            break;
        }
        index++;
    }
    return foundIndex;
}

- (void)addAssetDownload
{
    DownloadInfo *info = nil;
    NSString *assetFolder = nil;
    for (int index = 0; index<[_assets count]; index++)
    {
        info                                    = [_assets objectAtIndex:index];
        NSURL *url                              = [NSURL URLWithString:info.assetURL];
        NSURLRequest *request                   = [NSURLRequest requestWithURL:url];
        NSURLSessionDownloadTask *downloadTask  = [session downloadTaskWithRequest:request];

        DownloadHelper *assetDownload        = [[DownloadHelper alloc] initWithURL:url downloadTask:downloadTask];
        assetDownload.assetName                 = info.assetName;

        if (info.categoryId == 1)
        {
            assetFolder = [self getImagePath:info.assetName];
        }
        else if (info.categoryId == 2)
        {
            assetFolder = [self getVideoPath:info.assetName];
        }
        else if (info.categoryId == 3)
        {
            //assetFolder = [self getDBPath:info.assetName];
        }
        else
        {
            assetFolder = [self filePath:info.assetName];
        }
        assetDownload.assetFolder = assetFolder;
        [_assetsToDownload addObject:assetDownload];
    }
}

// Initialize the download, session and tasks
- (void)initialize
{
    for (DTEDownloadHelper *movieDownload in _assetsToDownload)
    {
        // Cancel each task
        NSURLSessionDownloadTask *downloadTask = movieDownload.downloadTask;
        [downloadTask cancel];
    }

    // Cancel all tasks and invalidate the session (also releasing the delegate)
    [session invalidateAndCancel];
    session = nil;

    _assetsToDownload = [[NSMutableArray alloc] init];

    // Create a session configuration passing in the session ID
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"DTEDownloadBackground"];
    sessionConfiguration.discretionary = YES;
    session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
    [self addAssetDownload];
    // Reset the UI
    downloading = NO;
    [self downloadFiles];

}


// Download handler
- (void)downloadFiles
{
    if ([_assetsToDownload count] > 0)
    {
        // Acquire the appropriate downloadTask and respond appropriately to the user's selection
        NSURLSessionDownloadTask * downloadTask = [_assetsToDownload[0] downloadTask];
        if (downloadTask.state == NSURLSessionTaskStateCompleted)
        {
            // Download is complete.  Play movie.
            // NSURL *movieURL = [NSURL fileURLWithPath:[_assetsToDownload[0] localPath]];
        }
        else if (downloadTask.state == NSURLSessionTaskStateSuspended)
        {
            // If suspended and not already downloading, resume transfer.
            if (!downloading)
            {
                [self showHUD:[NSString stringWithFormat:@"Downloading %@",[_assetsToDownload[0] assetName]]];
                [downloadTask resume];
                downloading = YES;
            }
        }
        else if (downloadTask.state == NSURLSessionTaskStateRunning)
        {
            // If already downloading, pause the transfer.
            [downloadTask suspend];
            downloading = NO;
        }

    }
}

- (void)downloadAssets
{
    _assets = [self retreiveAssets];    // Getting the resource details from the database
    if (![_assets count])
    {
        // Hide progress
    }
    [self addAssetDownload];
    [self downloadFiles];
}
@end

问题:

有时它会下载第一个文件并停在那里,下一次它不会下载任何东西。直到现在我都找不到问题,因为这个问题我浪费了将近一天的时间。请帮我找出问题所在。提前致谢。

最佳答案

使用后台 session 时,旧的下载请求可以在 session 之间持续存在。您是否尝试过使用 getTasksWithCompletionHandler 检查旧的、未完成的后台任务?我苦恼了一段时间,直到我意识到当我的应用程序启动时,它可能会在旧的后台请求之后积压。如果您在该后台 session 中有任何无效请求,一切都会得到一点备份。

此外,您的应用委托(delegate)是否处理 handleEventsForBackgroundURLSession 方法、重新实例化后台 session 并保存传递给您的应用的 completionHandler?您的 NSURLSessiondelegate 是否正在调用该完成处理程序(大概在 URLSessionDidFinishEventsForBackgroundURLSession: 方法中)?您要确保清理这些后台 session 。我在您的代码片段中没有看到任何此方法,但为了简洁起见,您可能省略了它。

可以在 URL Loading System Programming Guide: Using NSURLSession后台传输注意事项部分找到对此的讨论。指导。此外,在 WWDC 2013 的 40 分钟内显示了这方面的示例 What’s New in Foundation Networking视频。

关于ios - 多个文件下载有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24158104/

相关文章:

iphone - 什么可能导致崩溃?

swift - 如何使用 URLSession 从 HTTP 请求中获取 JSON 对象的特定属性

ios - 如何使用 NSURLSession block 从 API 调用 API

iOS NSURLSessionUploadTask 响应数据

ios - 按优先顺序在后台下载许多文件(照片、视频)

ios - 为 NSURLSessionDownloadTask 静音未实现的协议(protocol)方法警告

ios - swift 。按 n 个元素加载 collectionView

iphone - 我可以使用此代码依赖此 "default"更新间隔(加速计)吗?

ios - 使用 DocumentPicker 选择多个文件 - iOS

ios - 使用 urlsessiondownloadtask 从 url 下载文件后,文件无法打开