Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 52d39c03f8
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 763 lines (578 sloc) 21.207 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
//
// DTDownloadCache.m
// DTFoundation
//
// Created by Oliver Drobnik on 4/20/12.
// Copyright (c) 2012 Cocoanetics. All rights reserved.
//

#import "DTDownloadCache.h"

#import "NSString+DTPaths.h"
#import "DTCachedFile.h"
#import "DTDownload.h"
#import "NSString+DTUtilities.h"

#import <ImageIO/CGImageSource.h>
#import "NSString+DTFormatNumbers.h"
#import "DTAsyncFileDeleter.h"

NSString *DTDownloadCacheDidCacheFileNotification = @"DTDownloadCacheDidCacheFile";

@interface DTDownloadCache ()

- (void)_setupCoreDataStack;
- (DTCachedFile *)_cachedFileForURL:(NSURL *)URL inContext:(NSManagedObjectContext *)context;
- (NSUInteger)_currentDiskUsageInContext:(NSManagedObjectContext *)context;
- (void)_commitContext:(NSManagedObjectContext *)context;

@end

@implementation DTDownloadCache
{
// Core Data Stack
NSManagedObjectModel *_managedObjectModel;
NSPersistentStoreCoordinator *_persistentStoreCoordinator;
NSManagedObjectContext *_managedObjectContext;

// Internals
NSMutableDictionary *_downloads;
NSMutableArray *_downloadQueue;
NSMutableSet *_activeDownloads;

// memory cache for certain types, e.g. images
NSCache *_memoryCache;

NSUInteger _maxNumberOfConcurrentDownloads;
NSUInteger _diskCapacity;

// completion handling
NSMutableDictionary *_completionHandlers;

// maintenance
dispatch_queue_t _maintenanceQueue;
dispatch_queue_t _storeQueue;
}

+ (DTDownloadCache *)sharedInstance
{
static dispatch_once_t onceToken;
static DTDownloadCache *_sharedInstance;

dispatch_once(&onceToken, ^{
_sharedInstance = [[DTDownloadCache alloc] init];
});

return _sharedInstance;
}

- (id)init
{
self = [super init];
{
_maintenanceQueue = dispatch_queue_create("DTDownloadCache Maintenance", 0);
_storeQueue = dispatch_queue_create("DTDownloadCache Store", 0);

[self _setupCoreDataStack];

_downloads = [[NSMutableDictionary alloc] init];
_downloadQueue = [[NSMutableArray alloc] init];
_activeDownloads = [[NSMutableSet alloc] init];

_memoryCache = [[NSCache alloc] init];

_maxNumberOfConcurrentDownloads = 1;
_diskCapacity = 1024*1024*20; // 20 MB

_completionHandlers = [[NSMutableDictionary alloc] init];
}

return self;
}

#pragma mark Queue Handling

- (void)_enqueueDownloadForURL:(NSURL *)URL option:(DTDownloadCacheOption)option
{
DTDownload *download = [[DTDownload alloc] initWithURL:URL];
download.delegate = self;

if (option == DTDownloadCacheOptionReturnCacheAndLoadIfChanged)
{
DTCachedFile *cachedFile = [self _cachedFileForURL:URL inContext:_managedObjectContext];

if (cachedFile)
{
NSString *cachedETag = cachedFile.entityTagIdentifier;
NSDate *lastModifiedDate = cachedFile.lastModifiedDate;

__weak DTDownloadCache *weakself = self;

download.responseHandler = ^(DTDownload *download, NSDictionary *headers) {
BOOL shouldCancel = NO;

if (cachedETag)
{
if ([download.downloadEntityTag isEqualToString:cachedETag])
{
shouldCancel = YES;
}
}

if (lastModifiedDate)
{
if ([download.lastModifiedDate isEqualToDate:lastModifiedDate])
{
shouldCancel = YES;
}
}

if (shouldCancel)
{
[download cancel];
[weakself _removeDownloadFromQueue:download];
}
};
}
}


[_downloads setObject:download forKey:URL];
[_downloadQueue addObject:download];
}

- (void)_removeDownloadFromQueue:(DTDownload *)download
{
[_activeDownloads removeObject:download];
[_downloads removeObjectForKey:download.URL];
[_downloadQueue removeObject:download];

// remove a handler if it exists
DTDownloadCacheDataCompletionBlock completion = [_completionHandlers objectForKey:download.URL];

if (completion)
{
[_completionHandlers removeObjectForKey:download.URL];
}
}

- (void)_startNextQueuedDownload
{
NSUInteger numberLoading = 0;

for (DTDownload *nextDownload in [_downloadQueue reverseObjectEnumerator])
{
if (numberLoading<_maxNumberOfConcurrentDownloads)
{
if (![nextDownload isLoading])
{
[_activeDownloads addObject:nextDownload];
[nextDownload startWithResume:YES];
}

numberLoading++;
}
}
}

- (void)_cancelDownloadsOverConcurrencyLimit
{
NSUInteger numberLoading = 0;

for (DTDownload *nextDownload in [_downloadQueue reverseObjectEnumerator])
{
if ([nextDownload isLoading])
{
numberLoading++;

if (numberLoading<=_maxNumberOfConcurrentDownloads)
{
// leave it be
}
else
{
// cancel
[nextDownload cancel];

[_activeDownloads removeObject:nextDownload];

// cancel ditches the delegate, lets restore that
nextDownload.delegate = self;
}

}
}

NSLog(@"Loading Downloads: %d", numberLoading);
}


#pragma mark External Methods


- (NSData *)cachedDataForURL:(NSURL *)URL option:(DTDownloadCacheOption)option
{
// TODO: make this thread-safe so it can be called from background threads
if (dispatch_get_current_queue() != dispatch_get_main_queue())
{
__block NSData *retData;

dispatch_sync(dispatch_get_main_queue(), ^{
retData = [self cachedDataForURL:URL option:option];
});

return retData;
}

NSData *retData = nil;

DTCachedFile *existingCacheEntry = [self _cachedFileForURL:URL inContext:_managedObjectContext];

if (existingCacheEntry)
{
retData = existingCacheEntry.fileData;

if (option == DTDownloadCacheOptionReturnCacheAndLoadAlways)
{
[_managedObjectContext deleteObject:existingCacheEntry];
}
else
{
existingCacheEntry.lastAccessDate = [NSDate date];
}

[self _commitContext:_managedObjectContext];
}

if (option == DTDownloadCacheOptionNeverLoad)
{
return retData;
}

if (retData && option == DTDownloadCacheOptionLoadIfNotCached)
{
return retData;
}

// we don't have a cache entry, need to load

DTDownload *download = [_downloads objectForKey:URL];

if (download)
{
// already in queue, give it higher prio
if (![download isLoading])
{
// move it to end of LIFO queue
[_downloadQueue removeObject:download];
[_downloadQueue addObject:download];
}

return nil;
}

[self _enqueueDownloadForURL:URL option:option];
[self _startNextQueuedDownload];

return retData;
}

- (NSUInteger)currentDiskUsage
{
return [self _currentDiskUsageInContext:_managedObjectContext];
}

#pragma mark DTDownload

- (void)download:(DTDownload *)download didFailWithError:(NSError *)error
{
[self _removeDownloadFromQueue:download];

[self _startNextQueuedDownload];
}

- (void)download:(DTDownload *)download didFinishWithFile:(NSString *)path
{
dispatch_async(_storeQueue, ^{
// create context for background
NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
tmpContext.persistentStoreCoordinator = _persistentStoreCoordinator;


// check if URL already exists
DTCachedFile *cachedFile = [self _cachedFileForURL:download.URL inContext:tmpContext];

if (!cachedFile)
{
// create a new entity
cachedFile = (DTCachedFile *)[NSEntityDescription insertNewObjectForEntityForName:@"DTCachedFile" inManagedObjectContext:tmpContext];
}

cachedFile.lastAccessDate = [NSDate date];
cachedFile.expirationDate = [NSDate distantFuture];
cachedFile.lastModifiedDate = download.lastModifiedDate;
NSData *data = [NSData dataWithContentsOfMappedFile:path];
cachedFile.entityTagIdentifier = download.downloadEntityTag;
cachedFile.fileData = data;
cachedFile.fileSize = [NSNumber numberWithLongLong:download.totalBytes];
cachedFile.contentType = download.MIMEType;
cachedFile.remoteURL = [download.URL absoluteString];

[self _commitContext:tmpContext];

dispatch_sync(dispatch_get_main_queue(), ^{
// execute completion block if there is one registered
DTDownloadCacheDataCompletionBlock completion = [_completionHandlers objectForKey:download.URL];

if (completion)
{
completion(data);

[_completionHandlers removeObjectForKey:download.URL];
}

// send notification
[[NSNotificationCenter defaultCenter] postNotificationName:DTDownloadCacheDidCacheFileNotification object:download.URL];

// we transfered the file into the database, so we don't need it any more
[[DTAsyncFileDeleter sharedInstance] removeItemAtPath:path];
});
});

[self _removeDownloadFromQueue:download];

[self _startNextQueuedDownload];
}


#pragma mark CoreData Stack

- (NSManagedObjectModel *)_model
{
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] init];

// create the entity
NSEntityDescription *entity = [[NSEntityDescription alloc] init];
[entity setName:@"DTCachedFile"];
[entity setManagedObjectClassName:@"DTCachedFile"];

// create the attributes
NSMutableArray *properties = [NSMutableArray array];

NSAttributeDescription *remoteURLAttribute = [[NSAttributeDescription alloc] init];
[remoteURLAttribute setName:@"remoteURL"];
[remoteURLAttribute setAttributeType:NSStringAttributeType];
[remoteURLAttribute setOptional:NO];
[remoteURLAttribute setIndexed:YES];
[properties addObject:remoteURLAttribute];

NSAttributeDescription *fileDataAttribute = [[NSAttributeDescription alloc] init];
[fileDataAttribute setName:@"fileData"];
[fileDataAttribute setAttributeType:NSBinaryDataAttributeType];
[fileDataAttribute setOptional:NO];
[fileDataAttribute setAllowsExternalBinaryDataStorage:YES];
[properties addObject:fileDataAttribute];

NSAttributeDescription *lastAccessDateAttribute = [[NSAttributeDescription alloc] init];
[lastAccessDateAttribute setName:@"lastAccessDate"];
[lastAccessDateAttribute setAttributeType:NSDateAttributeType];
[lastAccessDateAttribute setOptional:NO];
[properties addObject:lastAccessDateAttribute];

NSAttributeDescription *lastModifiedDateAttribute = [[NSAttributeDescription alloc] init];
[lastModifiedDateAttribute setName:@"lastModifiedDate"];
[lastModifiedDateAttribute setAttributeType:NSDateAttributeType];
[lastModifiedDateAttribute setOptional:YES];
[properties addObject:lastModifiedDateAttribute];

NSAttributeDescription *expirationDateAttribute = [[NSAttributeDescription alloc] init];
[expirationDateAttribute setName:@"expirationDate"];
[expirationDateAttribute setAttributeType:NSDateAttributeType];
[expirationDateAttribute setOptional:NO];
[properties addObject:expirationDateAttribute];

NSAttributeDescription *contentTypeAttribute = [[NSAttributeDescription alloc] init];
[contentTypeAttribute setName:@"contentType"];
[contentTypeAttribute setAttributeType:NSStringAttributeType];
[contentTypeAttribute setOptional:NO];
[properties addObject:contentTypeAttribute];

NSAttributeDescription *fileSizeAttribute = [[NSAttributeDescription alloc] init];
[fileSizeAttribute setName:@"fileSize"];
[fileSizeAttribute setAttributeType:NSInteger32AttributeType];
[fileSizeAttribute setOptional:NO];
[properties addObject:fileSizeAttribute];

NSAttributeDescription *entityTagIdentifierAttribute = [[NSAttributeDescription alloc] init];
[entityTagIdentifierAttribute setName:@"entityTagIdentifier"];
[entityTagIdentifierAttribute setAttributeType:NSStringAttributeType];
[entityTagIdentifierAttribute setOptional:YES];
[properties addObject:entityTagIdentifierAttribute];

// add attributes to entity
[entity setProperties:properties];

// add entity to model
[model setEntities:[NSArray arrayWithObject:entity]];

return model;
}

- (void)_setupCoreDataStack
{
// setup managed object model

/*
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DTDownloadCache" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
*/

// in code
    _managedObjectModel = [self _model];

// setup persistent store coordinator
NSURL *storeURL = [NSURL fileURLWithPath:[[NSString cachesPath] stringByAppendingPathComponent:@"DTDownload.cache"]];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
// inconsistent model/store
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:NULL];

// retry once
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}

// create MOC
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:_persistentStoreCoordinator];

// subscribe to change notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];
}

// returned objects can only be used from the same context
- (DTCachedFile *)_cachedFileForURL:(NSURL *)URL inContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DTCachedFile"];

request.predicate = [NSPredicate predicateWithFormat:@"remoteURL == %@", [URL absoluteString]];
request.fetchLimit = 1;

NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];

if (!results)
{
NSLog(@"error occured fetching %@", [error localizedDescription]);
}

return [results lastObject];
}

- (void)_commitContext:(NSManagedObjectContext *)context
{
NSError *error;

if (![context save:&error])
{
NSLog(@"error occured saving %@", [error localizedDescription]);
}
}

- (void)_mocDidSaveNotification:(NSNotification *)notification
{
// ignore change notifications for the main MOC

NSManagedObjectContext *savedContext = [notification object];

if (_managedObjectContext == savedContext)
{
return;
}

if (_managedObjectContext.persistentStoreCoordinator != savedContext.persistentStoreCoordinator)
{
// that's another database
return;
}

dispatch_sync(dispatch_get_main_queue(), ^{
// merge in the changes
[_managedObjectContext mergeChangesFromContextDidSaveNotification:notification];

// shedule a maintenance run after a couple of seconds
SEL selector = @selector(_runMaintenance);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
[self performSelector:selector withObject:nil afterDelay:10.0f];
});
}

#pragma mark Maintenance

- (NSUInteger)_currentDiskUsageInContext:(NSManagedObjectContext *)context
{
NSExpression *ex = [NSExpression expressionForFunction:@"sum:"
arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"fileSize"]]];

    NSExpressionDescription *ed = [[NSExpressionDescription alloc] init];
    [ed setName:@"result"];
    [ed setExpression:ex];
    [ed setExpressionResultType:NSInteger64AttributeType];

    NSArray *properties = [NSArray arrayWithObject:ed];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setPropertiesToFetch:properties];
    [request setResultType:NSDictionaryResultType];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DTCachedFile"
inManagedObjectContext:context];
    [request setEntity:entity];

    NSArray *results = [context executeFetchRequest:request error:nil];
    NSDictionary *resultsDictionary = [results objectAtIndex:0];
    NSNumber *resultValue = [resultsDictionary objectForKey:@"result"];

    return [resultValue unsignedIntegerValue];
}

- (void)_removeExpiredFilesInContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DTCachedFile"];
request.propertiesToFetch = [NSArray arrayWithObject:@"expirationDate"];

request.predicate = [NSPredicate predicateWithFormat:@"expirationDate < %@", [NSDate date]];

NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];

if (!results)
{
NSLog(@"error occured fetching %@", [error localizedDescription]);
return;
}

for (NSManagedObject *oneObject in results)
{
[context deleteObject:oneObject];
}
}

- (void)_removeFilesOverCapacity:(NSUInteger)capacity inContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DTCachedFile"];
request.propertiesToFetch = [NSArray arrayWithObjects:@"fileSize", @"lastAccessDate", nil];

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"lastAccessDate" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sort];

NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];

if (!results)
{
NSLog(@"error occured fetching %@", [error localizedDescription]);
return;
}

long long capacitySoFar = 0;

for (DTCachedFile *cachedFile in results)
{
long long fileSize = [cachedFile.fileSize longLongValue];

capacitySoFar += fileSize;

if (capacitySoFar > capacity)
{
NSLog(@"over capacity: removed: %@ %lld", cachedFile.remoteURL, capacitySoFar);
[context deleteObject:cachedFile];
}
}
}

- (void)_runMaintenance
{
dispatch_async(_maintenanceQueue, ^{
// create context for background
NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
tmpContext.persistentStoreCoordinator = _persistentStoreCoordinator;

NSUInteger diskUsageBeforeMaintenance = [self _currentDiskUsageInContext:tmpContext];

// remove all expired files
[self _removeExpiredFilesInContext:tmpContext];

// prune oldest accessed files so that we get below disk usage limit
if (diskUsageBeforeMaintenance>_diskCapacity)
{
[self _removeFilesOverCapacity:_diskCapacity inContext:tmpContext];
}

// only commit if there are actually modifications
if ([tmpContext hasChanges])
{
[self _commitContext:tmpContext];
}

NSUInteger diskUsageAfterMaintenance = [self _currentDiskUsageInContext:tmpContext];

NSLog(@"Running Maintenance, Usage Before: %@, After: %@", [NSString stringByFormattingBytes:diskUsageBeforeMaintenance], [NSString stringByFormattingBytes:diskUsageAfterMaintenance]);
});
}

#pragma mark Completion Blocks

- (void)_registerCompletion:(DTDownloadCacheDataCompletionBlock)completion forURL:(NSURL *)URL
{
[_completionHandlers setObject:[completion copy] forKey:URL];
}

#pragma mark Properties

- (void)setMaxNumberOfConcurrentDownloads:(NSUInteger)maxNumberOfConcurrentDownloads
{
if (_maxNumberOfConcurrentDownloads != maxNumberOfConcurrentDownloads)
{
BOOL needsTrim = (maxNumberOfConcurrentDownloads < _maxNumberOfConcurrentDownloads);

NSAssert(maxNumberOfConcurrentDownloads>0, @"maximum number of concurrent downloads cannot be zero");
_maxNumberOfConcurrentDownloads = maxNumberOfConcurrentDownloads;

NSLog(@"Concurrent Downloads set to %d", maxNumberOfConcurrentDownloads);

// starts/stops enough downloads to match the max number
[self _startNextQueuedDownload];

if (needsTrim)
{
[self _cancelDownloadsOverConcurrencyLimit];
}
}
}

- (void)setDiskCapacity:(NSUInteger)diskCapacity
{
if (diskCapacity!=_diskCapacity)
{
_diskCapacity = diskCapacity;

[self _runMaintenance];
}
}

@synthesize maxNumberOfConcurrentDownloads = _maxNumberOfConcurrentDownloads;
@synthesize diskCapacity = _diskCapacity;

@end



@implementation DTDownloadCache (Images)

//TODO: make this thread-safe to be called from background threads

- (UIImage *)cachedImageForURL:(NSURL *)URL option:(DTDownloadCacheOption)option
{
// try memory cache first
UIImage *cachedImage = [_memoryCache objectForKey:URL];

if (cachedImage)
{
return cachedImage;
}

// try file cache
NSData *data = [self cachedDataForURL:URL option:option];

if (!data)
{
return nil;
}

    @try {
        cachedImage = [UIImage imageWithData:data];
    }
    @catch (NSException *exception) {
        NSLog(@"%@", exception);
    }
    @finally {
    }

if (!cachedImage)
{
NSLog(@"Illegal Data cached for %@", URL);
        
        [_memoryCache removeObjectForKey:URL];
return nil;
}

// put in memory cache
NSUInteger cost = (NSUInteger)(cachedImage.size.width * cachedImage.size.height);
[_memoryCache setObject:cachedImage forKey:URL cost:cost];

return cachedImage;
}

- (UIImage *)cachedImageForURL:(NSURL *)URL option:(DTDownloadCacheOption)option completion:(DTDownloadCacheImageCompletionBlock)completion
{
UIImage *cachedImage = [self cachedImageForURL:URL option:option];

if (cachedImage)
{
return cachedImage;
}

// register handler
if (completion)
{
DTDownloadCacheDataCompletionBlock internalBlock = ^(NSData *data)
{
// make an image out of the data
UIImage *cachedImage = [UIImage imageWithData:data];

if (!cachedImage)
{
NSLog(@"Illegal Data cached for %@", URL);
return;
}

// put in memory cache
NSUInteger cost = (NSUInteger)(cachedImage.size.width * cachedImage.size.height);
[_memoryCache setObject:cachedImage forKey:URL cost:cost];

// execute wrapped completion block
completion(cachedImage);
};

[self _registerCompletion:internalBlock forURL:URL];
}

return nil;
}


@end
Something went wrong with that request. Please try again.