【发布时间】: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