VLCNetworkImageView.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*****************************************************************************
  2. * VLC for iOS
  3. *****************************************************************************
  4. * Copyright (c) 2015 VideoLAN. All rights reserved.
  5. * $Id$
  6. *
  7. * Authors: Tobias Conradi <videolan # tobias-conradi.de>
  8. *
  9. * Refer to the COPYING file of the official project for license.
  10. *****************************************************************************/
  11. #import "VLCNetworkImageView.h"
  12. @implementation VLCNetworkImageView
  13. static NSCache *sharedImageCache = nil;
  14. + (void)setSharedImageCache:(NSCache *)sharedCache {
  15. sharedImageCache = sharedCache;
  16. }
  17. + (NSCache *)sharedImageCache {
  18. if (!sharedImageCache) {
  19. sharedImageCache = [[NSCache alloc] init];
  20. [sharedImageCache setCountLimit:50];
  21. }
  22. return sharedImageCache;
  23. }
  24. - (UIImage *)cacheImageForURL:(NSURL *)url {
  25. UIImage *image = [[self.class sharedImageCache] objectForKey:url];
  26. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  27. return image;
  28. }
  29. return nil;
  30. }
  31. - (void)cancelLoading {
  32. [self.downloadTask cancel];
  33. self.downloadTask = nil;
  34. }
  35. - (void)setImageWithURL:(NSURL *)url {
  36. [self cancelLoading];
  37. UIImage *cachedImage = [self cacheImageForURL:url];
  38. if (cachedImage) {
  39. self.image = cachedImage;
  40. } else {
  41. __weak typeof(self) weakSelf = self;
  42. NSURLSession *sharedSession = [NSURLSession sharedSession];
  43. self.downloadTask = [sharedSession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  44. if (!data) {
  45. return;
  46. }
  47. UIImage *image = [UIImage imageWithData:data];
  48. if (!image) { return; }
  49. [[[weakSelf class] sharedImageCache] setObject:image forKey:url];
  50. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  51. __strong typeof(weakSelf) strongSelf = weakSelf;
  52. if ([strongSelf.downloadTask.originalRequest.URL isEqual:url]) {
  53. strongSelf.image = image;
  54. strongSelf.downloadTask = nil;
  55. }
  56. }];
  57. }];
  58. }
  59. }
  60. @end