| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE.md file. | |
| 4 | |
| 5 #import "ImagePresenter.h" | |
| 6 | |
| 7 @interface ImagePresenter () | |
| 8 @property id<ImageCache> imageCache; | |
| 9 @end | |
| 10 | |
| 11 @implementation ImagePresenter | |
| 12 | |
| 13 - (void)setCache:(id<ImageCache>)cache { | |
| 14 self.imageCache = cache; | |
| 15 } | |
| 16 | |
| 17 - (void)setDefaultImage:(UIImage*)defaultImage { | |
| 18 self.image = defaultImage; | |
| 19 } | |
| 20 | |
| 21 - (void)presentImageFromData:(NSData*) imageData { | |
| 22 self.image = [UIImage imageWithData:imageData]; | |
| 23 } | |
| 24 | |
| 25 - (void)patchImage:(ImagePatch*)patch { | |
| 26 if (patch.url.changed) { | |
| 27 [self performSelectorOnMainThread:@selector(loadImageFromUrl:) | |
| 28 withObject:patch.url.current | |
| 29 waitUntilDone:NO]; | |
| 30 } | |
| 31 } | |
| 32 | |
| 33 - (void)presentImage:(ImageNode*)node { | |
| 34 [self performSelectorOnMainThread:@selector(loadImageFromUrl:) | |
| 35 withObject:node.url | |
| 36 waitUntilDone:NO]; | |
| 37 } | |
| 38 | |
| 39 - (void)loadImageFromUrl:(NSString*)url { | |
| 40 assert(NSThread.isMainThread); | |
| 41 | |
| 42 if (self.imageCache == nil) { | |
| 43 dispatch_async(dispatch_get_global_queue(0, 0), ^{ | |
| 44 NSData* imageData = | |
| 45 [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]]; | |
| 46 [self presentImageFromData:imageData]; | |
| 47 }); | |
| 48 } else { | |
| 49 id cachedImage = [self.imageCache get:url]; | |
| 50 if (cachedImage != nil) { | |
| 51 if ([cachedImage isKindOfClass:NSMutableArray.class]) { | |
| 52 [cachedImage addObject:self]; | |
| 53 } else { | |
| 54 [self presentImageFromData:cachedImage]; | |
| 55 } | |
| 56 } else { | |
| 57 NSMutableArray* waitingImages = [[NSMutableArray alloc] init]; | |
| 58 [waitingImages addObject:self]; | |
| 59 [self.imageCache put:url value:waitingImages]; | |
| 60 | |
| 61 dispatch_async(dispatch_get_global_queue(0, 0), ^{ | |
| 62 NSData* imageData = | |
| 63 [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]]; | |
| 64 | |
| 65 if (imageData == nil) return; | |
| 66 | |
| 67 dispatch_async(dispatch_get_main_queue(), ^{ | |
| 68 NSMutableArray* queue = [self.imageCache get:url]; | |
| 69 [self.imageCache put:url value:imageData]; | |
| 70 | |
| 71 [queue enumerateObjectsUsingBlock:^(ImagePresenter* imagePresenter, | |
| 72 NSUInteger idx, | |
| 73 BOOL* stop) { | |
| 74 [imagePresenter presentImageFromData:imageData]; | |
| 75 }]; | |
| 76 }); | |
| 77 }); | |
| 78 } | |
| 79 } | |
| 80 } | |
| 81 | |
| 82 @end | |
| OLD | NEW |