【问题标题】:Download Multiple Images Sequentially using NSURLSession downloadTask in Objective C在Objective C中使用NSURLSession downloadTask顺序下载多个图像
【发布时间】:2019-02-14 08:55:53
【问题描述】:

我的应用提供了从我们的服务器下载 3430 张高分辨率图像的选项,每张图像的大小为 50k - 600k 字节。

最初的方法是只下载所有这些 - 但我们意识到这会产生很多 NSURLErrorTimedOut 错误并使我们的程序崩溃。然后我们实现了它,以便我们下载所有图像,但一次分批下载 100 个图像。 Someone on SO 建议我们实际上像这样实现我们的下载:

创建需要下载的所有文件 URL 的列表。

编写您的代码,以便按顺序下载这些 URL。 IE。做 在前一个文件完成之前,不要让它开始下载文件 完成(或失败,您决定暂时跳过)。

使用 NSURLSession 支持将单个文件下载到 文件夹,不要使用代码获取 NSData 并保存文件 你自己。这样,您的应用程序不需要在运行时 下载完成。

确保您可以判断文件是否已下载或 不会,以防您的下载中断或手机重新启动 在下载中。你可以例如通过比较他们的名字来做到这一点(如果 它们足够独特),或者将注释保存到 plist 中,让您 将下载的文件与它来自的 URL 或其他任何内容相匹配 在您的案例中构成识别特征。

在启动时,检查是否所有文件都在那里。如果没有,把缺失的 上面下载列表中的,依次下载,如#2。

在您开始下载任何内容之前(包括下载 上一次下载完成或失败后的下一个文件),执行 使用 Apple 的可达性 API 进行可达性检查 SystemConfiguration.framework。这会告诉你用户是否有 完全没有连接,无论您使用的是 WiFi 还是蜂窝网络(在 一般来说,您不想通过以下方式下载大量文件 蜂窝,大多数蜂窝连接都是按流量计费的)。

我们在此处创建所有图片的列表以供下载:

- (void)generateImageURLList:(BOOL)batchDownloadImagesFromServer
{
    NSError* error;
    NSFetchRequest* leafletURLRequest = [[[NSFetchRequest alloc] init] autorelease];
    NSEntityDescription* leafletURLDescription = [NSEntityDescription entityForName:@"LeafletURL" inManagedObjectContext:managedObjectContext];
    [leafletURLRequest setEntity:leafletURLDescription];        
    numberOfImages = [managedObjectContext countForFetchRequest:leafletURLRequest error:&error];
    NSPredicate* thumbnailPredicate = [NSPredicate predicateWithFormat:@"thumbnailLocation like %@", kLocationServer];
    [leafletURLRequest setPredicate:thumbnailPredicate];
    self.uncachedThumbnailArray = [managedObjectContext executeFetchRequest:leafletURLRequest error:&error];      
    NSPredicate* hiResPredicate = [NSPredicate predicateWithFormat:@"hiResImageLocation != %@", kLocationCache];
    [leafletURLRequest setPredicate:hiResPredicate];
    self.uncachedHiResImageArray = [managedObjectContext executeFetchRequest:leafletURLRequest error:&error];
}

我们使用 NSURLSession 通过调用 hitServerForUrl 并实现 didFinishDownloadingToURL 将单个图像下载到文件夹:

- (void)hitServerForUrl:(NSURL*)requestUrl {
    NSURLSessionConfiguration *defaultConfigurationObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigurationObject delegate:self delegateQueue: nil];

    NSURLSessionDownloadTask *fileDownloadTask = [defaultSession downloadTaskWithURL:requestUrl];

    [fileDownloadTask resume];

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {


    if (isThumbnail)
    {
        leafletURL.thumbnailLocation = kLocationCache;
    }
    else
    {
        leafletURL.hiResImageLocation = kLocationCache;
    }

    // Filename to write to
    NSString* filePath = [leafletURL pathForImageAtLocation:kLocationCache isThumbnail:isThumbnail isRetina:NO];

    // If it's a retina image, append the "@2x"
    if (isRetina_) {
        filePath = [filePath stringByReplacingOccurrencesOfString:@".jpg" withString:@"@2x.jpg"];
    }

    NSString* dir = [filePath stringByDeletingLastPathComponent];

    [managedObjectContext save:nil];

    NSError* error;
    [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:&error];

    NSURL *documentURL = [NSURL fileURLWithPath:filePath];

    NSLog(@"file path : %@", filePath);
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //Remove the old file from directory
    }

    [[NSFileManager defaultManager] moveItemAtURL:location
                                            toURL:documentURL
                                            error:&error];
    if (error){
        //Handle error here
    }
}

这段代码调用loadImage,它调用`hitServer:

-(void)downloadImagesFromServer{

    [self generateImageURLList:NO];

    [leafletImageLoaderQueue removeAllObjects];
    numberOfHiResImageLeft = [uncachedHiResImageArray count];

    for ( LeafletURL* aLeafletURL in uncachedHiResImageArray)
        {
            //// Do the same thing again, except set isThumb = NO. ////
            LeafletImageLoader* hiResImageLoader = [[LeafletImageLoader alloc] initWithDelegate:self];
            [leafletImageLoaderQueue addObject:hiResImageLoader]; // do this before making connection!! //

            [hiResImageLoader loadImage:aLeafletURL isThumbnail:NO   isBatchDownload:YES];

            //// Adding object to array already retains it, so it's safe to release it here. ////
            [hiResImageLoader release];
            uncachedHiResIndex++;
            NSLog(@"uncached hi res index: %ld, un cached hi res image array size: %lu", (long)uncachedHiResIndex, (unsigned long)[uncachedHiResImageArray count]);
    }

}

- (void)loadImage:(LeafletURL*)leafletURLInput isThumbnail:(BOOL)isThumbnailInput isBatchDownload:(BOOL)isBatchDownload isRetina:(BOOL)isRetina
{

    isRetina_ = isRetina;

    if (mConnection)
    {
        [mConnection cancel];
        [mConnection release];
        mConnection = nil;
    }
    if (mImageData)
    {
        [mImageData release];
        mImageData = nil;
    }

    self.leafletURL = leafletURLInput;
    self.isThumbnail = isThumbnailInput;

    NSString* location = (self.isThumbnail) ?leafletURL.thumbnailLocation :leafletURL.hiResImageLocation;

    //// Check if the image needs to be downloaded from server. If it is a batch download, then override the local resources////
    if ( ([location isEqualToString:kLocationServer] || (isBatchDownload && [location isEqualToString:kLocationResource])) && self.leafletURL.rawURL != nil )
    {
        //NSLog(@"final loadimage called server");
        //// tell the delegate to get ride of the old image while waiting. ////
        if([delegate respondsToSelector:@selector(leafletImageLoaderWillBeginLoadingImage:)])
        {
            [delegate leafletImageLoaderWillBeginLoadingImage:self];
        }

        mImageData = [[NSMutableData alloc] init];

        NSURL* url = [NSURL URLWithString:[leafletURL pathForImageOnServerUsingThumbnail:self.isThumbnail isRetina:isRetina]];
        [self hitServerForUrl:url];

    }

    //// if not, tell the delegate that the image is already cached. ////
    else
    {
        if([delegate respondsToSelector:@selector(leafletImageLoaderDidFinishLoadingImage:)])
        {

            [delegate leafletImageLoaderDidFinishLoadingImage:self];

        }
    }
}

目前,我正在尝试弄清楚如何按顺序下载图像,这样在最后一张图像下载完成之前我们不会调用hitServer我需要下载吗?在后台?感谢您的建议!

【问题讨论】:

  • 这个问题没有意义;目前,你没有打电话给hitServerever,所以不清楚你认为它应该做什么。另外,hitServer 是完全错误的;您应该拥有自己的 NSURLSession 并提前创建和保留,并在整个过程中使用它;这也将解决您的“调整”问题。
  • NSOperationQueue 可能有帮助吗?此外,您可能会终止用户的数据计划。不过,也许这不是一个考虑因素。

标签: ios objective-c nsurlsession nsurlsessiondownloadtask


【解决方案1】:

我的应用提供了从我们的服务器下载 3430 张高分辨率图像的选项,每张图像的大小为 50k - 600k 字节。

这似乎是on-demand resources 的工作。只需将这些文件转换为从您自己的服务器获取的按需资源,并让系统在自己的甜蜜时间负责下载它们。

【讨论】:

    【解决方案2】:

    这听起来很像架构问题。如果您在不限制下载的情况下启动下载,那么您当然会开始遇到超时和其他问题。想想其他应用程序以及它们的作用。使用户能够进行多次下载的应用程序通常会限制一次下载的可能性。例如,iTunes 可以将数千个下载排队,但一次只能运行 3 个。一次只限制一个只会减慢您的用户的速度。您需要考虑用户可用带宽的平衡。

    另一部分是再次考虑您的用户想要什么。您的每个用户都需要每一张图片吗?我不知道您为他们提供什么,但在大多数访问图像或音乐等资源的应用程序中,下载内容和时间取决于用户。因此他们只下载他们感兴趣的内容。所以我建议只下载用户正在查看或以某种方式请求他们想要下载的内容。

    【讨论】:

    • 目前,是的,这里是仅下载他们正在查看的图像的选项!他们还被问及是否愿意下载所有高分辨率图像,除非他们同意,否则我们不会这样做。即使我使用@matt 建议的按需资源来实现下载,它仍然会太多吗?
    猜你喜欢
    • 2015-11-26
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多