From 4642054655e4122a229802f41b426fca7ae8522f Mon Sep 17 00:00:00 2001 From: Geoff MacDonald Date: Tue, 29 Apr 2014 12:40:34 -0400 Subject: [PATCH 1/3] added support for image downloading using alternative sources with NSProgress updated sample app with three cases. --- .../JTSImageVC.xcodeproj/project.pbxproj | 86 +++ .../JTSImageVC/Base.lproj/Main.storyboard | 53 +- .../JTSImageVC/JTSImageVC/JTSViewController.h | 2 + .../JTSImageVC/JTSImageVC/JTSViewController.m | 67 ++- Sample App/JTSImageVC/JTSImageVC/jimpam.gif | Bin 0 -> 25845 bytes .../SDWebImage/NSData+ImageContentType.h | 10 + .../SDWebImage/NSData+ImageContentType.m | 40 ++ .../JTSImageVC/SDWebImage/SDImageCache.h | 187 +++++++ .../JTSImageVC/SDWebImage/SDImageCache.m | 500 ++++++++++++++++++ .../JTSImageVC/SDWebImage/SDWebImageCompat.h | 62 +++ .../JTSImageVC/SDWebImage/SDWebImageCompat.m | 41 ++ .../JTSImageVC/SDWebImage/SDWebImageDecoder.h | 18 + .../JTSImageVC/SDWebImage/SDWebImageDecoder.m | 72 +++ .../SDWebImage/SDWebImageDownloader.h | 151 ++++++ .../SDWebImage/SDWebImageDownloader.m | 215 ++++++++ .../SDWebImageDownloaderOperation.h | 24 + .../SDWebImageDownloaderOperation.m | 397 ++++++++++++++ .../JTSImageVC/SDWebImage/SDWebImageManager.h | 205 +++++++ .../JTSImageVC/SDWebImage/SDWebImageManager.m | 254 +++++++++ .../SDWebImage/SDWebImageOperation.h | 15 + .../SDWebImage/SDWebImagePrefetcher.h | 87 +++ .../SDWebImage/SDWebImagePrefetcher.m | 138 +++++ .../JTSImageVC/SDWebImage/UIButton+WebCache.h | 179 +++++++ .../JTSImageVC/SDWebImage/UIButton+WebCache.m | 114 ++++ .../JTSImageVC/SDWebImage/UIImage+GIF.h | 19 + .../JTSImageVC/SDWebImage/UIImage+GIF.m | 158 ++++++ .../SDWebImage/UIImage+MultiFormat.h | 15 + .../SDWebImage/UIImage+MultiFormat.m | 39 ++ .../SDWebImage/UIImageView+WebCache.h | 150 ++++++ .../SDWebImage/UIImageView+WebCache.m | 116 ++++ Source/JTSImageViewController.h | 23 + Source/JTSImageViewController.m | 79 ++- 32 files changed, 3504 insertions(+), 12 deletions(-) create mode 100644 Sample App/JTSImageVC/JTSImageVC/jimpam.gif create mode 100644 Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h create mode 100644 Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDImageCache.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDImageCache.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h create mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m create mode 100644 Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h create mode 100644 Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m create mode 100755 Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h create mode 100755 Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m create mode 100644 Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h create mode 100644 Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m create mode 100644 Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h create mode 100644 Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m diff --git a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj index 00c2b64..ef3cfaa 100644 --- a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj +++ b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj @@ -28,6 +28,19 @@ 7F9A794218E75712000CAA69 /* UIImage+JTSImageEffects.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F9A794118E75712000CAA69 /* UIImage+JTSImageEffects.m */; }; 7FE0848218E7C5C600F2F6B4 /* banecat.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 7FE0848118E7C5C600F2F6B4 /* banecat.jpg */; }; 7FE95B4E18EE0E8100F18370 /* UIApplication+JTSImageViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FE95B4D18EE0E8100F18370 /* UIApplication+JTSImageViewController.m */; }; + C30DCC4B191001B500B8445C /* NSData+ImageContentType.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC33191001B500B8445C /* NSData+ImageContentType.m */; }; + C30DCC4C191001B500B8445C /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC35191001B500B8445C /* SDImageCache.m */; }; + C30DCC4D191001B500B8445C /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC37191001B500B8445C /* SDWebImageCompat.m */; }; + C30DCC4E191001B500B8445C /* SDWebImageDecoder.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC39191001B500B8445C /* SDWebImageDecoder.m */; }; + C30DCC4F191001B500B8445C /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */; }; + C30DCC50191001B500B8445C /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */; }; + C30DCC51191001B500B8445C /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3F191001B500B8445C /* SDWebImageManager.m */; }; + C30DCC52191001B500B8445C /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */; }; + C30DCC53191001B500B8445C /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC44191001B500B8445C /* UIButton+WebCache.m */; }; + C30DCC54191001B500B8445C /* UIImage+GIF.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC46191001B500B8445C /* UIImage+GIF.m */; }; + C30DCC55191001B500B8445C /* UIImage+MultiFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */; }; + C30DCC56191001B500B8445C /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */; }; + C30DCC58191007E900B8445C /* jimpam.gif in Resources */ = {isa = PBXBuildFile; fileRef = C30DCC57191007E900B8445C /* jimpam.gif */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -73,6 +86,32 @@ 7FE0848118E7C5C600F2F6B4 /* banecat.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = banecat.jpg; sourceTree = ""; }; 7FE95B4C18EE0E8100F18370 /* UIApplication+JTSImageViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIApplication+JTSImageViewController.h"; path = "../../../Source/UIApplication+JTSImageViewController.h"; sourceTree = ""; }; 7FE95B4D18EE0E8100F18370 /* UIApplication+JTSImageViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIApplication+JTSImageViewController.m"; path = "../../../Source/UIApplication+JTSImageViewController.m"; sourceTree = ""; }; + C30DCC32191001B500B8445C /* NSData+ImageContentType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+ImageContentType.h"; sourceTree = ""; }; + C30DCC33191001B500B8445C /* NSData+ImageContentType.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+ImageContentType.m"; sourceTree = ""; }; + C30DCC34191001B500B8445C /* SDImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDImageCache.h; sourceTree = ""; }; + C30DCC35191001B500B8445C /* SDImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDImageCache.m; sourceTree = ""; }; + C30DCC36191001B500B8445C /* SDWebImageCompat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageCompat.h; sourceTree = ""; }; + C30DCC37191001B500B8445C /* SDWebImageCompat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageCompat.m; sourceTree = ""; }; + C30DCC38191001B500B8445C /* SDWebImageDecoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDecoder.h; sourceTree = ""; }; + C30DCC39191001B500B8445C /* SDWebImageDecoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDecoder.m; sourceTree = ""; }; + C30DCC3A191001B500B8445C /* SDWebImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloader.h; sourceTree = ""; }; + C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloader.m; sourceTree = ""; }; + C30DCC3C191001B500B8445C /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloaderOperation.h; sourceTree = ""; }; + C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloaderOperation.m; sourceTree = ""; }; + C30DCC3E191001B500B8445C /* SDWebImageManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageManager.h; sourceTree = ""; }; + C30DCC3F191001B500B8445C /* SDWebImageManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageManager.m; sourceTree = ""; }; + C30DCC40191001B500B8445C /* SDWebImageOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageOperation.h; sourceTree = ""; }; + C30DCC41191001B500B8445C /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImagePrefetcher.h; sourceTree = ""; }; + C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImagePrefetcher.m; sourceTree = ""; }; + C30DCC43191001B500B8445C /* UIButton+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+WebCache.h"; sourceTree = ""; }; + C30DCC44191001B500B8445C /* UIButton+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+WebCache.m"; sourceTree = ""; }; + C30DCC45191001B500B8445C /* UIImage+GIF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+GIF.h"; sourceTree = ""; }; + C30DCC46191001B500B8445C /* UIImage+GIF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+GIF.m"; sourceTree = ""; }; + C30DCC47191001B500B8445C /* UIImage+MultiFormat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+MultiFormat.h"; sourceTree = ""; }; + C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+MultiFormat.m"; sourceTree = ""; }; + C30DCC49191001B500B8445C /* UIImageView+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+WebCache.h"; sourceTree = ""; }; + C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+WebCache.m"; sourceTree = ""; }; + C30DCC57191007E900B8445C /* jimpam.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = jimpam.gif; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -102,6 +141,7 @@ 7F9A78F218E754A7000CAA69 = { isa = PBXGroup; children = ( + C30DCC31191001B500B8445C /* SDWebImage */, 7F9A793318E754D9000CAA69 /* Source */, 7F9A790418E754A7000CAA69 /* Sample App */, 7F9A792318E754A7000CAA69 /* Sample App Tests */, @@ -133,6 +173,7 @@ 7F9A790418E754A7000CAA69 /* Sample App */ = { isa = PBXGroup; children = ( + C30DCC57191007E900B8445C /* jimpam.gif */, 7FE0848118E7C5C600F2F6B4 /* banecat.jpg */, 7F9A790D18E754A7000CAA69 /* JTSAppDelegate.h */, 7F9A790E18E754A7000CAA69 /* JTSAppDelegate.m */, @@ -196,6 +237,38 @@ path = JTSImageVC; sourceTree = ""; }; + C30DCC31191001B500B8445C /* SDWebImage */ = { + isa = PBXGroup; + children = ( + C30DCC32191001B500B8445C /* NSData+ImageContentType.h */, + C30DCC33191001B500B8445C /* NSData+ImageContentType.m */, + C30DCC34191001B500B8445C /* SDImageCache.h */, + C30DCC35191001B500B8445C /* SDImageCache.m */, + C30DCC36191001B500B8445C /* SDWebImageCompat.h */, + C30DCC37191001B500B8445C /* SDWebImageCompat.m */, + C30DCC38191001B500B8445C /* SDWebImageDecoder.h */, + C30DCC39191001B500B8445C /* SDWebImageDecoder.m */, + C30DCC3A191001B500B8445C /* SDWebImageDownloader.h */, + C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */, + C30DCC3C191001B500B8445C /* SDWebImageDownloaderOperation.h */, + C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */, + C30DCC3E191001B500B8445C /* SDWebImageManager.h */, + C30DCC3F191001B500B8445C /* SDWebImageManager.m */, + C30DCC40191001B500B8445C /* SDWebImageOperation.h */, + C30DCC41191001B500B8445C /* SDWebImagePrefetcher.h */, + C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */, + C30DCC43191001B500B8445C /* UIButton+WebCache.h */, + C30DCC44191001B500B8445C /* UIButton+WebCache.m */, + C30DCC45191001B500B8445C /* UIImage+GIF.h */, + C30DCC46191001B500B8445C /* UIImage+GIF.m */, + C30DCC47191001B500B8445C /* UIImage+MultiFormat.h */, + C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */, + C30DCC49191001B500B8445C /* UIImageView+WebCache.h */, + C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */, + ); + path = SDWebImage; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -273,6 +346,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + C30DCC58191007E900B8445C /* jimpam.gif in Resources */, 7FE0848218E7C5C600F2F6B4 /* banecat.jpg in Resources */, 7F9A791718E754A7000CAA69 /* Images.xcassets in Resources */, 7F9A790918E754A7000CAA69 /* InfoPlist.strings in Resources */, @@ -295,14 +369,26 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + C30DCC4E191001B500B8445C /* SDWebImageDecoder.m in Sources */, + C30DCC51191001B500B8445C /* SDWebImageManager.m in Sources */, + C30DCC4B191001B500B8445C /* NSData+ImageContentType.m in Sources */, + C30DCC4D191001B500B8445C /* SDWebImageCompat.m in Sources */, 7F9A793918E75558000CAA69 /* JTSImageInfo.m in Sources */, 7FE95B4E18EE0E8100F18370 /* UIApplication+JTSImageViewController.m in Sources */, 7F9A791518E754A7000CAA69 /* JTSViewController.m in Sources */, + C30DCC53191001B500B8445C /* UIButton+WebCache.m in Sources */, + C30DCC52191001B500B8445C /* SDWebImagePrefetcher.m in Sources */, + C30DCC50191001B500B8445C /* SDWebImageDownloaderOperation.m in Sources */, 7F9A793C18E75593000CAA69 /* JTSSimpleImageDownloader.m in Sources */, + C30DCC56191001B500B8445C /* UIImageView+WebCache.m in Sources */, 7F9A790F18E754A7000CAA69 /* JTSAppDelegate.m in Sources */, + C30DCC55191001B500B8445C /* UIImage+MultiFormat.m in Sources */, 7F9A794218E75712000CAA69 /* UIImage+JTSImageEffects.m in Sources */, + C30DCC4C191001B500B8445C /* SDImageCache.m in Sources */, 7F9A793F18E755F6000CAA69 /* JTSAnimatedGIFUtility.m in Sources */, 7F9A793618E75541000CAA69 /* JTSImageViewController.m in Sources */, + C30DCC54191001B500B8445C /* UIImage+GIF.m in Sources */, + C30DCC4F191001B500B8445C /* SDWebImageDownloader.m in Sources */, 7F9A790B18E754A7000CAA69 /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Sample App/JTSImageVC/JTSImageVC/Base.lproj/Main.storyboard b/Sample App/JTSImageVC/JTSImageVC/Base.lproj/Main.storyboard index bd62073..dcd9e3e 100644 --- a/Sample App/JTSImageVC/JTSImageVC/Base.lproj/Main.storyboard +++ b/Sample App/JTSImageVC/JTSImageVC/Base.lproj/Main.storyboard @@ -1,5 +1,5 @@ - + @@ -16,19 +16,65 @@ - + + + + + + + @@ -37,6 +83,7 @@ + diff --git a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h index 36c3f09..b5ffcf0 100644 --- a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h +++ b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h @@ -11,5 +11,7 @@ @interface JTSViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *bigImageButton; +@property (weak, nonatomic) IBOutlet UIButton *simpleImageButton; +@property (weak, nonatomic) IBOutlet UIButton *customBigImageButton; @end diff --git a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m index ddfc7f6..afd5ea8 100644 --- a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m +++ b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m @@ -11,6 +11,8 @@ #import "JTSImageViewController.h" #import "JTSImageInfo.h" +#import "SDWebImageManager.h" + @interface JTSViewController () @end @@ -19,15 +21,16 @@ @implementation JTSViewController - (void)viewDidLoad { [super viewDidLoad]; - [self.bigImageButton addTarget:self action:@selector(bigButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; [self.bigImageButton setAccessibilityLabel:@"Photo of a cat wearing a Bane costume."]; + [self.simpleImageButton setAccessibilityLabel:@"Photo of jim and pam in love"]; + [self.customBigImageButton setAccessibilityLabel:@"Photo of jim and pam in love"]; } - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } -- (void)bigButtonTapped:(id)sender { +- (IBAction)bigButtonTapped:(id)sender { // Create image info JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init]; @@ -41,10 +44,70 @@ - (void)bigButtonTapped:(id)sender { mode:JTSImageViewControllerMode_Image backgroundStyle:JTSImageViewControllerBackgroundStyle_ScaledDimmedBlurred]; + // Present the view controller. [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition]; } +- (IBAction)simpleButtonTapped:(id)sender { + // Create image info + JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init]; + imageInfo.imageURL = [NSURL URLWithString:@"http://i.imgur.com/iGRxQNb.gif"]; + imageInfo.referenceRect = self.simpleImageButton.frame; + imageInfo.referenceView = self.simpleImageButton.superview; + + // Setup view controller + JTSImageViewController *imageViewer = [[JTSImageViewController alloc] + initWithImageInfo:imageInfo + mode:JTSImageViewControllerMode_Image + backgroundStyle:JTSImageViewControllerBackgroundStyle_ScaledDimmedBlurred]; + + + // Present the view controller. + [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition]; +} + +- (IBAction)customBigButtonTapped:(id)sender { + //download image with custom progress from SDWebImage + + // Create image info + JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init]; + imageInfo.referenceRect = self.customBigImageButton.frame; + imageInfo.referenceView = self.customBigImageButton.superview; + + SDWebImageManager * manage= [SDWebImageManager sharedManager]; + //clear memory to test progress + SDImageCache *imageCache = [SDImageCache sharedImageCache]; + [imageCache clearMemory]; + [imageCache clearDisk]; + [imageCache cleanDisk]; + + __block NSProgress * progress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + + SDWebImageDownloaderProgressBlock sdBlock = ^(NSInteger receivedSize, NSInteger expectedSize) { + + [progress setCompletedUnitCount:receivedSize]; + [progress setTotalUnitCount:expectedSize]; + }; + + //with custom progress + JTSImageViewController *imageViewer = [[JTSImageViewController alloc] + initWithImageInfo:imageInfo + mode:JTSImageViewControllerMode_Image + backgroundStyle:JTSImageViewControllerBackgroundStyle_ScaledDimmedBlurred + customImageProgress:progress]; + + //hopefully url does not disappear + [manage downloadWithURL:[NSURL URLWithString:@"http://i.imgur.com/iGRxQNb.gif"] options:0 progress:sdBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + + [imageViewer customImageSetter:image]; + }]; + + // Present the view controller. + [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition]; + +} + @end diff --git a/Sample App/JTSImageVC/JTSImageVC/jimpam.gif b/Sample App/JTSImageVC/JTSImageVC/jimpam.gif new file mode 100644 index 0000000000000000000000000000000000000000..f180a6ec20933d0508173008f36cbd80352227bf GIT binary patch literal 25845 zcmb5VbyOTr&^EfbJ0t{`MHT|V35zbl7Fl4i1c%@RcXxMKG{F~lcL+{!SsX$jAp{S> zA&|@OeeeCgzi-buGpA2YSJj;9nSQG3>3=K#z5z&;6`%?LG&D4T($fL>w+?s%z{0@9 z#KgdQI$>d9VdD_u;yg7H0s=fjG7@rfG7>T}if44sDJW^E$jGRfscGox85tQVp0fa1 z7=UyPj12!i0|;=@SkNxe(8vJ)h5+;c008Gd6aTlNV_-gMM#IH>5*w2O&@j-S3}WEm zU=rct;sDUlF~|UzSmez7*bq$|3Klb$kd)uJlmdkf{R>pjS!L7awt;YM*JpyFI_4H` z?qNku183C2Z{CMCHqWyO$!S@p77wy>h{z+5CI8j{xc^y}2ArkiQ*vq)%0~SEy|hV9 ziZgE4a(pusWEgtY;91KXRx-qQXokT(Arq_t`$BhJ#dj=nY&}9-~B>jIn(h-V`9MgnJ|09u(c=M?K>BYnO=s$qt)0lsNv@Pr)|C_L@qem*Q zM|FQ{>4zD{e}G%UM=E#!ymnrWKl!AAoB0E^jA?sVVT_3Xz0>(`{%gSujv<@}ap?#- zlP~vSsdDDtXa4}O6%rhbe*m%fTW$8gD}=A``u8;%5e-}GEjR8lM;zg0k1ium z)|a>E=#E~6FYrgd4_waq3ud_|-UcEW$6s$9|JUmx+m<1DOddf7Eeqec=l|4-2M{_aiRfA?=6c|~gV zT=51lIQ{+=Xx(md=gEI>b@>mlzl`&~TR@fI$mFW#AK*vfZSHn1`~CBWs-P$9GtM&? zPlBl@LG7cpxAk4%t9#vl0OH^$ZGC0tcgJ^DPrZ)YyzTt`mA?OszCLn_j3>!|Pwx33 z82Arx>~1o7O61x*!uq!==$5-LyO;JcJN|L8Z?Ndmy50KD^MCb4{q&0rDl`8FX!&37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zJ4j*Rs1L6I4oh!QpK!RP<|;OScTxRTY+H~$fk@6Ojf zR~KFS!K_Z1@`)H=cFr7eDG6I$Bbgnvs@#uc_TW;H^@?au=SYc`dx-sxdsG)ukzs`W zYc|fMiiqvxz$p+H&SbTDy0&hMQT33(C|6p$kC|fenEnCmiZne>XFtv1#L=8t{ngDk zlD7K}w`mo5i9KT$T7Sf3BTQkt9MpAv;@k8+J5Tp_9UV#M+(4RU1O{wWyR@eNUoHDz Qw{rZ?Ydr1`JpVWQe|zDLEC2ui literal 0 HcmV?d00001 diff --git a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h new file mode 100644 index 0000000..bb78bb0 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h @@ -0,0 +1,10 @@ +// +// Created by Fabrice Aneche on 06/01/14. +// Copyright (c) 2014 Dailymotion. All rights reserved. +// + +#import + +@interface NSData (ImageContentType) ++ (NSString *)contentTypeForImageData:(NSData *)data; +@end diff --git a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m new file mode 100644 index 0000000..6fb352d --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m @@ -0,0 +1,40 @@ +// +// Created by Fabrice Aneche on 06/01/14. +// Copyright (c) 2014 Dailymotion. All rights reserved. +// + +#import "NSData+ImageContentType.h" + + +@implementation NSData (ImageContentType) + ++ (NSString *)contentTypeForImageData:(NSData *)data { + uint8_t c; + [data getBytes:&c length:1]; + switch (c) { + case 0xFF: + return @"image/jpeg"; + case 0x89: + return @"image/png"; + case 0x47: + return @"image/gif"; + case 0x49: + case 0x4D: + return @"image/tiff"; + case 0x52: + // R as RIFF for WEBP + if ([data length] < 12) { + return nil; + } + + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; + if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { + return @"image/webp"; + } + + return nil; + } + return nil; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDImageCache.h b/Sample App/JTSImageVC/SDWebImage/SDImageCache.h new file mode 100644 index 0000000..2e1eed5 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDImageCache.h @@ -0,0 +1,187 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NS_ENUM(NSInteger, SDImageCacheType) { + /** + * The image wasn't available the SDWebImage caches, but was downloaded from the web. + */ + SDImageCacheTypeNone, + /** + * The image was obtained from the disk cache. + */ + SDImageCacheTypeDisk, + /** + * The image was obtained from the memory cache. + */ + SDImageCacheTypeMemory +}; + +typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); + +/** + * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed + * asynchronous so it doesn’t add unnecessary latency to the UI. + */ +@interface SDImageCache : NSObject + +/** + * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCost; + +/** + * The maximum length of time to keep an image in the cache, in seconds + */ +@property (assign, nonatomic) NSInteger maxCacheAge; + +/** + * The maximum size of the cache, in bytes. + */ +@property (assign, nonatomic) NSUInteger maxCacheSize; + +/** + * Returns global shared cache instance + * + * @return SDImageCache global instance + */ ++ (SDImageCache *)sharedImageCache; + +/** + * Init a new cache store with a specific namespace + * + * @param ns The namespace to use for this cache store + */ +- (id)initWithNamespace:(NSString *)ns; + +/** + * Add a read-only cache path to search for images pre-cached by SDImageCache + * Useful if you want to bundle pre-loaded images with your app + * + * @param path The path to use for this read-only cache path + */ +- (void)addReadOnlyCachePath:(NSString *)path; + +/** + * Store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage + * @param imageData The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Query the disk cache asynchronously. + * + * @param key The unique key used to store the wanted image + */ +- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; + +/** + * Query the memory cache synchronously. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; + +/** + * Query the disk cache synchronously after checking the memory cache. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key; + +/** + * Remove the image from memory and disk cache synchronously + * + * @param key The unique image cache key + */ +- (void)removeImageForKey:(NSString *)key; + +/** + * Remove the image from memory and optionally disk cache synchronously + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES + */ +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; + +/** + * Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Clear all disk cached images. Non-blocking method - returns immediately. + * @param completionBlock An block that should be executed after cache expiration completes (optional) + */ +- (void)clearDiskOnCompletion:(void (^)())completion; + +/** + * Clear all disk cached images + * @see clearDiskOnCompletion: + */ +- (void)clearDisk; + +/** + * Remove all expired cached image from disk. Non-blocking method - returns immediately. + * @param completionBlock An block that should be executed after cache expiration completes (optional) + */ +- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock; + +/** + * Remove all expired cached image from disk + * @see cleanDiskWithCompletionBlock: + */ +- (void)cleanDisk; + +/** + * Get the size used by the disk cache + */ +- (NSUInteger)getSize; + +/** + * Get the number of images in the disk cache + */ +- (int)getDiskCount; + +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock; + +/** + * Check if image exists in cache already + */ +- (BOOL)diskImageExistsWithKey:(NSString *)key; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDImageCache.m b/Sample App/JTSImageVC/SDWebImage/SDImageCache.m new file mode 100644 index 0000000..3f36e5e --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDImageCache.m @@ -0,0 +1,500 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCache.h" +#import "SDWebImageDecoder.h" +#import "UIImage+MultiFormat.h" +#import + +static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week +// PNG signature bytes and data (below) +static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; +static NSData *kPNGSignatureData = nil; + +BOOL ImageDataHasPNGPreffix(NSData *data); + +BOOL ImageDataHasPNGPreffix(NSData *data) { + NSUInteger pngSignatureLength = [kPNGSignatureData length]; + if ([data length] >= pngSignatureLength) { + if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { + return YES; + } + } + + return NO; +} + +@interface SDImageCache () + +@property (strong, nonatomic) NSCache *memCache; +@property (strong, nonatomic) NSString *diskCachePath; +@property (strong, nonatomic) NSMutableArray *customPaths; +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; + +@end + + +@implementation SDImageCache { + NSFileManager *_fileManager; +} + ++ (SDImageCache *)sharedImageCache { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; + }); + return instance; +} + +- (id)init { + return [self initWithNamespace:@"default"]; +} + +- (id)initWithNamespace:(NSString *)ns { + if ((self = [super init])) { + NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; + + // Create IO serial queue + _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); + + // Init default values + _maxCacheAge = kDefaultCacheMaxCacheAge; + + // Init the memory cache + _memCache = [[NSCache alloc] init]; + _memCache.name = fullNamespace; + + // Init the disk cache + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace]; + + dispatch_sync(_ioQueue, ^{ + _fileManager = [NSFileManager new]; + }); + +#if TARGET_OS_IPHONE + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(clearMemory) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(cleanDisk) + name:UIApplicationWillTerminateNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(backgroundCleanDisk) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + SDDispatchQueueRelease(_ioQueue); +} + +- (void)addReadOnlyCachePath:(NSString *)path { + if (!self.customPaths) { + self.customPaths = [NSMutableArray new]; + } + + if (![self.customPaths containsObject:path]) { + [self.customPaths addObject:path]; + } +} + +#pragma mark SDImageCache (private) + +- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { + NSString *filename = [self cachedFileNameForKey:key]; + return [path stringByAppendingPathComponent:filename]; +} + +- (NSString *)defaultCachePathForKey:(NSString *)key { + return [self cachePathForKey:key inPath:self.diskCachePath]; +} + +- (NSString *)cachedFileNameForKey:(NSString *)key { + const char *str = [key UTF8String]; + if (str == NULL) { + str = ""; + } + unsigned char r[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), r); + NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; + + return filename; +} + +#pragma mark ImageCache + +- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { + if (!image || !key) { + return; + } + + [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale]; + + if (toDisk) { + dispatch_async(self.ioQueue, ^{ + NSData *data = imageData; + + if (image && (recalculate || !data)) { +#if TARGET_OS_IPHONE + // We need to determine if the image is a PNG or a JPEG + // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) + // The first eight bytes of a PNG file always contain the following (decimal) values: + // 137 80 78 71 13 10 26 10 + + // We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly), + // we will consider it PNG to avoid loosing the transparency + BOOL imageIsPng = YES; + + // But if we have an image data, we will look at the preffix + if ([imageData length] >= [kPNGSignatureData length]) { + imageIsPng = ImageDataHasPNGPreffix(imageData); + } + + if (imageIsPng) { + data = UIImagePNGRepresentation(image); + } + else { + data = UIImageJPEGRepresentation(image, (CGFloat)1.0); + } +#else + data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; +#endif + } + + if (data) { + if (![_fileManager fileExistsAtPath:_diskCachePath]) { + [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + + [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; + } + }); + } +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key { + [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { + [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; +} + +- (BOOL)diskImageExistsWithKey:(NSString *)key { + __block BOOL exists = NO; + dispatch_sync(_ioQueue, ^{ + exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; + }); + + return exists; +} + +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { + return [self.memCache objectForKey:key]; +} + +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key { + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + return image; + } + + // Second check the disk cache... + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage) { + CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + return diskImage; +} + +- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { + NSString *defaultPath = [self defaultCachePathForKey:key]; + NSData *data = [NSData dataWithContentsOfFile:defaultPath]; + if (data) { + return data; + } + + for (NSString *path in self.customPaths) { + NSString *filePath = [self cachePathForKey:key inPath:path]; + NSData *imageData = [NSData dataWithContentsOfFile:filePath]; + if (imageData) { + return imageData; + } + } + + return nil; +} + +- (UIImage *)diskImageForKey:(NSString *)key { + NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; + if (data) { + UIImage *image = [UIImage sd_imageWithData:data]; + image = [self scaledImageForKey:key image:image]; + image = [UIImage decodedImageWithImage:image]; + return image; + } + else { + return nil; + } +} + +- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock { + NSOperation *operation = [NSOperation new]; + + if (!doneBlock) return nil; + + if (!key) { + doneBlock(nil, SDImageCacheTypeNone); + return nil; + } + + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + doneBlock(image, SDImageCacheTypeMemory); + return nil; + } + + dispatch_async(self.ioQueue, ^{ + if (operation.isCancelled) { + return; + } + + @autoreleasepool { + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage) { + CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + doneBlock(diskImage, SDImageCacheTypeDisk); + }); + } + }); + + return operation; +} + +- (void)removeImageForKey:(NSString *)key { + [self removeImageForKey:key fromDisk:YES]; +} + +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { + if (key == nil) { + return; + } + + [self.memCache removeObjectForKey:key]; + + if (fromDisk) { + dispatch_async(self.ioQueue, ^{ + [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; + }); + } +} + +- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { + self.memCache.totalCostLimit = maxMemoryCost; +} + +- (NSUInteger)maxMemoryCost { + return self.memCache.totalCostLimit; +} + +- (void)clearMemory { + [self.memCache removeAllObjects]; +} + +- (void)clearDisk { + [self clearDiskOnCompletion:nil]; +} + +- (void)clearDiskOnCompletion:(void (^)())completion +{ + dispatch_async(self.ioQueue, ^{ + [_fileManager removeItemAtPath:self.diskCachePath error:nil]; + [_fileManager createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); +} + +- (void)cleanDisk { + [self cleanDiskWithCompletionBlock:nil]; +} + +- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock { + dispatch_async(self.ioQueue, ^{ + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; + + // This enumerator prefetches useful properties for our cache files. + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:resourceKeys + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; + NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; + NSUInteger currentCacheSize = 0; + + // Enumerate all of the files in the cache directory. This loop has two purposes: + // + // 1. Removing files that are older than the expiration date. + // 2. Storing file attributes for the size-based cleanup pass. + for (NSURL *fileURL in fileEnumerator) { + NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; + + // Skip directories. + if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { + continue; + } + + // Remove files that are older than the expiration date; + NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; + if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { + [_fileManager removeItemAtURL:fileURL error:nil]; + continue; + } + + // Store a reference to this file and account for its total size. + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; + [cacheFiles setObject:resourceValues forKey:fileURL]; + } + + // If our remaining disk cache exceeds a configured maximum size, perform a second + // size-based cleanup pass. We delete the oldest files first. + if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { + // Target half of our maximum cache size for this cleanup pass. + const NSUInteger desiredCacheSize = self.maxCacheSize / 2; + + // Sort the remaining cache files by their last modification time (oldest first). + NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent + usingComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; + }]; + + // Delete files until we fall below our desired cache size. + for (NSURL *fileURL in sortedFiles) { + if ([_fileManager removeItemAtURL:fileURL error:nil]) { + NSDictionary *resourceValues = cacheFiles[fileURL]; + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; + + if (currentCacheSize < desiredCacheSize) { + break; + } + } + } + } + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); +} + +- (void)backgroundCleanDisk { + UIApplication *application = [UIApplication sharedApplication]; + __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ + // Clean up any unfinished task business by marking where you + // stopped or ending the task outright. + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; + + // Start the long-running task and return immediately. + [self cleanDiskWithCompletionBlock:^{ + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; +} + +- (NSUInteger)getSize { + __block NSUInteger size = 0; + dispatch_sync(self.ioQueue, ^{ + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; + for (NSString *fileName in fileEnumerator) { + NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; + NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; + size += [attrs fileSize]; + } + }); + return size; +} + +- (int)getDiskCount { + __block int count = 0; + dispatch_sync(self.ioQueue, ^{ + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; + for (__unused NSString *fileName in fileEnumerator) { + count += 1; + } + }); + return count; +} + +- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + dispatch_async(self.ioQueue, ^{ + NSUInteger fileCount = 0; + NSUInteger totalSize = 0; + + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:@[NSFileSize] + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + for (NSURL *fileURL in fileEnumerator) { + NSNumber *fileSize; + [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; + totalSize += [fileSize unsignedIntegerValue]; + fileCount += 1; + } + + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(fileCount, totalSize); + }); + } + }); +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h new file mode 100644 index 0000000..2d90d3c --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h @@ -0,0 +1,62 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#ifdef __OBJC_GC__ +#error SDWebImage does not support Objective-C Garbage Collection +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 +#error SDWebImage doesn't support Deployement Target version < 5.0 +#endif + +#if !TARGET_OS_IPHONE +#import +#ifndef UIImage +#define UIImage NSImage +#endif +#ifndef UIImageView +#define UIImageView NSImageView +#endif +#else + +#import + +#endif + +#ifndef NS_ENUM +#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef NS_OPTIONS +#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#if OS_OBJECT_USE_OBJC + #undef SDDispatchQueueRelease + #undef SDDispatchQueueSetterSementics + #define SDDispatchQueueRelease(q) + #define SDDispatchQueueSetterSementics strong +#else +#undef SDDispatchQueueRelease +#undef SDDispatchQueueSetterSementics +#define SDDispatchQueueRelease(q) (dispatch_release(q)) +#define SDDispatchQueueSetterSementics assign +#endif + +extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); + +#define dispatch_main_sync_safe(block)\ + if ([NSThread isMainThread]) {\ + block();\ + }\ + else {\ + dispatch_sync(dispatch_get_main_queue(), block);\ + } diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m new file mode 100644 index 0000000..7f91153 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m @@ -0,0 +1,41 @@ +// +// SDWebImageCompat.m +// SDWebImage +// +// Created by Olivier Poitrey on 11/12/12. +// Copyright (c) 2012 Dailymotion. All rights reserved. +// + +#import "SDWebImageCompat.h" + +#if !__has_feature(objc_arc) +#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { + if ([image.images count] > 0) { + NSMutableArray *scaledImages = [NSMutableArray array]; + + for (UIImage *tempImage in image.images) { + [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; + } + + return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; + } + else { + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { + CGFloat scale = 1.0; + if (key.length >= 8) { + // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) + NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; + if (range.location != NSNotFound) { + scale = 2.0; + } + } + + UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; + image = scaledImage; + } + return image; + } +} diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h new file mode 100644 index 0000000..0176a7b --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h @@ -0,0 +1,18 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +@interface UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m new file mode 100644 index 0000000..79ddb30 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDecoder.h" + +@implementation UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image { + if (image.images) { + // Do not decode animated images + return image; + } + + CGImageRef imageRef = image.CGImage; + CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); + CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; + + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); + BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || + infoMask == kCGImageAlphaNoneSkipFirst || + infoMask == kCGImageAlphaNoneSkipLast); + + // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. + // https://developer.apple.com/library/mac/#qa/qa1037/_index.html + if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + + // Set noneSkipFirst. + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } + // Some PNGs tell us they have alpha but only 3 components. Odd. + else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } + + // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. + CGContextRef context = CGBitmapContextCreate(NULL, + imageSize.width, + imageSize.height, + CGImageGetBitsPerComponent(imageRef), + 0, + colorSpace, + bitmapInfo); + CGColorSpaceRelease(colorSpace); + + // If failed, return undecompressed image + if (!context) return image; + + CGContextDrawImage(context, imageRect, imageRef); + CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; + CGImageRelease(decompressedImageRef); + return decompressedImage; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h new file mode 100644 index 0000000..0895997 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h @@ -0,0 +1,151 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { + SDWebImageDownloaderLowPriority = 1 << 0, + SDWebImageDownloaderProgressiveDownload = 1 << 1, + + /** + * By default, request prevent the of NSURLCache. With this flag, NSURLCache + * is used with default policies. + */ + SDWebImageDownloaderUseNSURLCache = 1 << 2, + + /** + * Call completion block with nil image/imageData if the image was read from NSURLCache + * (to be combined with `SDWebImageDownloaderUseNSURLCache`). + */ + + SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + + SDWebImageDownloaderContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageDownloaderHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL ceriticates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, + + /** + * Put the image in the high priority queue. + */ + SDWebImageDownloaderHighPriority = 1 << 7, + + +}; + +typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { + /** + * Default value. All download operations will execute in queue style (first-in-first-out). + */ + SDWebImageDownloaderFIFOExecutionOrder, + + /** + * All download operations will execute in stack style (last-in-first-out). + */ + SDWebImageDownloaderLIFOExecutionOrder +}; + +extern NSString *const SDWebImageDownloadStartNotification; +extern NSString *const SDWebImageDownloadStopNotification; + +typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); + +typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +@property (assign, nonatomic) NSInteger maxConcurrentDownloads; + +/** + * Shows the current amount of downloads that still need to be downloaded + */ + +@property (readonly, nonatomic) NSUInteger currentDownloadCount; + + +/** + * The timeout value (in seconds) for the download operation. Default: 15.0. + */ +@property (assign, nonatomic) NSTimeInterval downloadTimeout; + + +/** + * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; + ++ (SDWebImageDownloader *)sharedDownloader; + +/** + * Set filter to pick headers for downloading image HTTP request. + * + * This block will be invoked for each downloading image request, returned + * NSDictionary will be used as headers in corresponding HTTP request. + */ +@property (nonatomic, strong) NSDictionary *(^headersFilter)(NSURL *url, NSDictionary *headers); + +/** + * Set a value for a HTTP header to be appended to each download HTTP request. + * + * @param value The value for the header field. Use `nil` value to remove the header. + * @param field The name of the header field to set. + */ +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; + +/** + * Returns the value of the specified HTTP header field. + * + * @return The value associated with the header field field, or `nil` if there is no corresponding header field. + */ +- (NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param progressBlock A block called repeatedly while the image is downloading + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveDownload isn't use. With the + * SDWebImageDownloaderProgressiveDownload option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A cancellable SDWebImageOperation + */ +- (id )downloadImageWithURL:(NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m new file mode 100644 index 0000000..5b7cae2 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m @@ -0,0 +1,215 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderOperation.h" +#import + +NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; + +static NSString *const kProgressCallbackKey = @"progress"; +static NSString *const kCompletedCallbackKey = @"completed"; + +@interface SDWebImageDownloader () + +@property (strong, nonatomic) NSOperationQueue *downloadQueue; +@property (weak, nonatomic) NSOperation *lastAddedOperation; +@property (strong, nonatomic) NSMutableDictionary *URLCallbacks; +@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; +// This queue is used to serialize the handling of the network responses of all the download operation in a single queue +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; + +@end + +@implementation SDWebImageDownloader + ++ (void)initialize { + // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) + // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import + if (NSClassFromString(@"SDNetworkActivityIndicator")) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; +#pragma clang diagnostic pop + + // Remove observer in case it was previously added. + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"startActivity") + name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"stopActivity") + name:SDWebImageDownloadStopNotification object:nil]; + } +} + ++ (SDWebImageDownloader *)sharedDownloader { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + _downloadQueue = [NSOperationQueue new]; + _downloadQueue.maxConcurrentOperationCount = 2; + _URLCallbacks = [NSMutableDictionary new]; + _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"]; + _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); + _downloadTimeout = 15.0; + } + return self; +} + +- (void)dealloc { + [self.downloadQueue cancelAllOperations]; + SDDispatchQueueRelease(_barrierQueue); +} + +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { + if (value) { + self.HTTPHeaders[field] = value; + } + else { + [self.HTTPHeaders removeObjectForKey:field]; + } +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + return self.HTTPHeaders[field]; +} + +- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { + _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; +} + +- (NSUInteger)currentDownloadCount { + return _downloadQueue.operationCount; +} + +- (NSInteger)maxConcurrentDownloads { + return _downloadQueue.maxConcurrentOperationCount; +} + +- (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock { + __block SDWebImageDownloaderOperation *operation; + __weak SDWebImageDownloader *wself = self; + + [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ + NSTimeInterval timeoutInterval = wself.downloadTimeout; + if (timeoutInterval == 0.0) { + timeoutInterval = 15.0; + } + + // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; + request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); + request.HTTPShouldUsePipelining = YES; + if (wself.headersFilter) { + request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); + } + else { + request.allHTTPHeaderFields = wself.HTTPHeaders; + } + operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request + options:options + progress:^(NSInteger receivedSize, NSInteger expectedSize) { + if (!wself) return; + SDWebImageDownloader *sself = wself; + NSArray *callbacksForURL = [sself callbacksForURL:url]; + for (NSDictionary *callbacks in callbacksForURL) { + SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; + if (callback) callback(receivedSize, expectedSize); + } + } + completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { + if (!wself) return; + SDWebImageDownloader *sself = wself; + NSArray *callbacksForURL = [sself callbacksForURL:url]; + if (finished) { + [sself removeCallbacksForURL:url]; + } + for (NSDictionary *callbacks in callbacksForURL) { + SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; + if (callback) callback(image, data, error, finished); + } + } + cancelled:^{ + if (!wself) return; + SDWebImageDownloader *sself = wself; + [sself removeCallbacksForURL:url]; + }]; + + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } + + [wself.downloadQueue addOperation:operation]; + if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { + // Emulate LIFO execution order by systematically adding new operations as last operation's dependency + [wself.lastAddedOperation addDependency:operation]; + wself.lastAddedOperation = operation; + } + }]; + + return operation; +} + +- (void)addProgressCallback:(void (^)(NSInteger, NSInteger))progressBlock andCompletedBlock:(void (^)(UIImage *, NSData *data, NSError *, BOOL))completedBlock forURL:(NSURL *)url createCallback:(void (^)())createCallback { + // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. + if (url == nil) { + if (completedBlock != nil) { + completedBlock(nil, nil, nil, NO); + } + return; + } + + dispatch_barrier_sync(self.barrierQueue, ^{ + BOOL first = NO; + if (!self.URLCallbacks[url]) { + self.URLCallbacks[url] = [NSMutableArray new]; + first = YES; + } + + // Handle single download of simultaneous download request for the same URL + NSMutableArray *callbacksForURL = self.URLCallbacks[url]; + NSMutableDictionary *callbacks = [NSMutableDictionary new]; + if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; + if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; + [callbacksForURL addObject:callbacks]; + self.URLCallbacks[url] = callbacksForURL; + + if (first) { + createCallback(); + } + }); +} + +- (NSArray *)callbacksForURL:(NSURL *)url { + __block NSArray *callbacksForURL; + dispatch_sync(self.barrierQueue, ^{ + callbacksForURL = self.URLCallbacks[url]; + }); + return [callbacksForURL copy]; +} + +- (void)removeCallbacksForURL:(NSURL *)url { + dispatch_barrier_async(self.barrierQueue, ^{ + [self.URLCallbacks removeObjectForKey:url]; + }); +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..154a4e5 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h @@ -0,0 +1,24 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +@interface SDWebImageDownloaderOperation : NSOperation + +@property (strong, nonatomic, readonly) NSURLRequest *request; +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +- (id)initWithRequest:(NSURLRequest *)request + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock + cancelled:(void (^)())cancelBlock; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..05783f8 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m @@ -0,0 +1,397 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageDecoder.h" +#import "UIImage+MultiFormat.h" +#import + +@interface SDWebImageDownloaderOperation () + +@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; +@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; +@property (copy, nonatomic) void (^cancelBlock)(); + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (assign, nonatomic) NSInteger expectedSize; +@property (strong, nonatomic) NSMutableData *imageData; +@property (strong, nonatomic) NSURLConnection *connection; +@property (strong, atomic) NSThread *thread; + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 +@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@end + +@implementation SDWebImageDownloaderOperation { + size_t width, height; + UIImageOrientation orientation; + BOOL responseFromCached; +} + +- (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock cancelled:(void (^)())cancelBlock { + if ((self = [super init])) { + _request = request; + _options = options; + _progressBlock = [progressBlock copy]; + _completedBlock = [completedBlock copy]; + _cancelBlock = [cancelBlock copy]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called + } + return self; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + self.finished = YES; + [self reset]; + return; + } + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 + if ([self shouldContinueWhenAppEntersBackground]) { + __weak __typeof__ (self) wself = self; + self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ + __strong __typeof (wself) sself = wself; + + if (sself) { + [sself cancel]; + + [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId]; + sself.backgroundTaskId = UIBackgroundTaskInvalid; + } + }]; + } +#endif + + self.executing = YES; + self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; + self.thread = [NSThread currentThread]; + } + + [self.connection start]; + + if (self.connection) { + if (self.progressBlock) { + self.progressBlock(0, NSURLResponseUnknownLength); + } + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; + + if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { + // Make sure to run the runloop in our background thread so it can process downloaded data + // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 + // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); + } + else { + CFRunLoopRun(); + } + + if (!self.isFinished) { + [self.connection cancel]; + [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; + } + } + else { + if (self.completedBlock) { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); + } + } + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif +} + +- (void)cancel { + @synchronized (self) { + if (self.thread) { + [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; + } + else { + [self cancelInternal]; + } + } +} + +- (void)cancelInternalAndStop { + [self cancelInternal]; + CFRunLoopStop(CFRunLoopGetCurrent()); +} + +- (void)cancelInternal { + if (self.isFinished) return; + [super cancel]; + if (self.cancelBlock) self.cancelBlock(); + + if (self.connection) { + [self.connection cancel]; + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + + // As we cancelled the connection, its callback won't be called and thus won't + // maintain the isFinished and isExecuting flags. + if (self.isExecuting) self.executing = NO; + if (!self.isFinished) self.finished = YES; + } + + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + self.cancelBlock = nil; + self.completedBlock = nil; + self.progressBlock = nil; + self.connection = nil; + self.imageData = nil; + self.thread = nil; +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isConcurrent { + return YES; +} + +#pragma mark NSURLConnection (delegate) + +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { + if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) { + NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; + self.expectedSize = expected; + if (self.progressBlock) { + self.progressBlock(0, expected); + } + + self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; + } + else { + [self.connection cancel]; + + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + if (self.completedBlock) { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); + } + + [self done]; + } +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { + [self.imageData appendData:data]; + + if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Get the total bytes downloaded + const NSInteger totalSize = self.imageData.length; + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL); + CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize); + + if (width + height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); + if (properties) { + NSInteger orientationValue = -1; + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &width); + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); + CFRelease(properties); + + // When we draw to Core Graphics, we lose orientation information, + // which means the image below born of initWithCGIImage will be + // oriented incorrectly sometimes. (Unlike the image born of initWithData + // in connectionDidFinishLoading.) So save it here and pass it on later. + orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; + } + + } + + if (width + height > 0 && totalSize < self.expectedSize) { + // Create the image + CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); + +#ifdef TARGET_OS_IPHONE + // Workaround for iOS anamorphic image + if (partialImageRef) { + const size_t partialHeight = CGImageGetHeight(partialImageRef); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); + CGColorSpaceRelease(colorSpace); + if (bmContext) { + CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); + CGImageRelease(partialImageRef); + partialImageRef = CGBitmapContextCreateImage(bmContext); + CGContextRelease(bmContext); + } + else { + CGImageRelease(partialImageRef); + partialImageRef = nil; + } + } +#endif + + if (partialImageRef) { + UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; + UIImage *scaledImage = [self scaledImageForKey:self.request.URL.absoluteString image:image]; + image = [UIImage decodedImageWithImage:scaledImage]; + CGImageRelease(partialImageRef); + dispatch_main_sync_safe(^{ + if (self.completedBlock) { + self.completedBlock(image, nil, nil, NO); + } + }); + } + } + + CFRelease(imageSource); + } + + if (self.progressBlock) { + self.progressBlock(self.imageData.length, self.expectedSize); + } +} + ++ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { + switch (value) { + case 1: + return UIImageOrientationUp; + case 3: + return UIImageOrientationDown; + case 8: + return UIImageOrientationLeft; + case 6: + return UIImageOrientationRight; + case 2: + return UIImageOrientationUpMirrored; + case 4: + return UIImageOrientationDownMirrored; + case 5: + return UIImageOrientationLeftMirrored; + case 7: + return UIImageOrientationRightMirrored; + default: + return UIImageOrientationUp; + } +} + +- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { + CFRunLoopStop(CFRunLoopGetCurrent()); + self.connection = nil; + + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; + + if (completionBlock) { + if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { + completionBlock(nil, nil, nil, YES); + self.completionBlock = nil; + [self done]; + } + else { + + UIImage *image = [UIImage sd_imageWithData:self.imageData]; + + image = [self scaledImageForKey:self.request.URL.absoluteString image:image]; + + if (!image.images) // Do not force decod animated GIFs + { + image = [UIImage decodedImageWithImage:image]; + } + + if (CGSizeEqualToSize(image.size, CGSizeZero)) { + completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); + } + else { + completionBlock(image, self.imageData, nil, YES); + } + self.completionBlock = nil; + [self done]; + } + } + else { + [self done]; + } +} + +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { + CFRunLoopStop(CFRunLoopGetCurrent()); + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + if (self.completedBlock) { + self.completedBlock(nil, nil, error, YES); + } + + [self done]; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { + responseFromCached = NO; // If this method is called, it means the response wasn't read from cache + if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { + // Prevents caching of responses + return nil; + } + else { + return cachedResponse; + } +} + +- (BOOL)shouldContinueWhenAppEntersBackground { + return self.options & SDWebImageDownloaderContinueInBackground; +} + +- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { + return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; +} + +- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { + BOOL trustAllCertificates = (self.options & SDWebImageDownloaderAllowInvalidSSLCertificates); + if (trustAllCertificates && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] + forAuthenticationChallenge:challenge]; + } + + [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h new file mode 100644 index 0000000..45598c4 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h @@ -0,0 +1,205 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDownloader.h" +#import "SDImageCache.h" + +typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { + /** + * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. + * This flag disable this blacklisting. + */ + SDWebImageRetryFailed = 1 << 0, + + /** + * By default, image downloads are started during UI interactions, this flags disable this feature, + * leading to delayed download on UIScrollView deceleration for instance. + */ + SDWebImageLowPriority = 1 << 1, + + /** + * This flag disables on-disk caching + */ + SDWebImageCacheMemoryOnly = 1 << 2, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + * By default, the image is only displayed once completely downloaded. + */ + SDWebImageProgressiveDownload = 1 << 3, + + /** + * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. + * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. + * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. + * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. + * + * Use this flag only if you can't make your URLs static with embeded cache busting parameter. + */ + SDWebImageRefreshCached = 1 << 4, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageContinueInBackground = 1 << 5, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageHandleCookies = 1 << 6, + + /** + * Enable to allow untrusted SSL ceriticates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageAllowInvalidSSLCertificates = 1 << 7, + + /** + * By default, image are loaded in the order they were queued. This flag move them to + * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which + * could take a while). + */ + SDWebImageHighPriority = 1 << 8 +}; + +typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType); + +typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished); + + +@class SDWebImageManager; + +@protocol SDWebImageManagerDelegate + +@optional + +/** + * Controls which image should be downloaded when the image is not found in the cache. + * + * @param imageManager The current `SDWebImageManager` + * @param imageURL The url of the image to be downloaded + * + * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. + */ +- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; + +/** + * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. + * NOTE: This method is called from a global queue in order to not to block the main thread. + * + * @param imageManager The current `SDWebImageManager` + * @param image The image to transform + * @param imageURL The url of the image to transform + * + * @return The transformed image object. + */ +- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; + +@end + +/** + * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. + * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). + * You can use this class directly to benefit from web image downloading with caching in another context than + * a UIView. + * + * Here is a simple example of how to use SDWebImageManager: + * + * @code + +SDWebImageManager *manager = [SDWebImageManager sharedManager]; +[manager downloadWithURL:imageURL + options:0 + progress:nil + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (image) { + // do something with image + } + }]; + + * @endcode + */ +@interface SDWebImageManager : NSObject + +@property (weak, nonatomic) id delegate; + +@property (strong, nonatomic, readonly) SDImageCache *imageCache; +@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; + +/** + * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can + * be used to remove dynamic part of an image URL. + * + * The following example sets a filter in the application delegate that will remove any query-string from the + * URL before to use it as a cache key: + * + * @code + +[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; +}]; + + * @endcode + */ +@property (strong) NSString *(^cacheKeyFilter)(NSURL *url); + +/** + * Returns global SDWebImageManager instance. + * + * @return SDWebImageManager shared instance + */ ++ (SDWebImageManager *)sharedManager; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. + * + * This parameter is required. + * + * This block has no return value and takes the requested UIImage as first parameter. + * In case of error the image parameter is nil and the second parameter may contain an NSError. + * + * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache + * or from the memory cache or from the network. + * + * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is + * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * @return Returns a cancellable NSOperation + */ +- (id )downloadWithURL:(NSURL *)url + options:(SDWebImageOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; + +/** + * Cancel all current opreations + */ +- (void)cancelAll; + +/** + * Check one or more operations running + */ +- (BOOL)isRunning; + +/** + * Check if image has already been cached + */ +- (BOOL)diskImageExistsForURL:(NSURL *)url; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m new file mode 100644 index 0000000..2e893ec --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m @@ -0,0 +1,254 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageManager.h" +#import + +@interface SDWebImageCombinedOperation : NSObject + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (copy, nonatomic) void (^cancelBlock)(); +@property (strong, nonatomic) NSOperation *cacheOperation; + +@end + +@interface SDWebImageManager () + +@property (strong, nonatomic, readwrite) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; +@property (strong, nonatomic) NSMutableArray *failedURLs; +@property (strong, nonatomic) NSMutableArray *runningOperations; + +@end + +@implementation SDWebImageManager + ++ (id)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _imageCache = [self createCache]; + _imageDownloader = [SDWebImageDownloader new]; + _failedURLs = [NSMutableArray new]; + _runningOperations = [NSMutableArray new]; + } + return self; +} + +- (SDImageCache *)createCache { + return [SDImageCache sharedImageCache]; +} + +- (NSString *)cacheKeyForURL:(NSURL *)url { + if (self.cacheKeyFilter) { + return self.cacheKeyFilter(url); + } + else { + return [url absoluteString]; + } +} + +- (BOOL)diskImageExistsForURL:(NSURL *)url { + NSString *key = [self cacheKeyForURL:url]; + return [self.imageCache diskImageExistsWithKey:key]; +} + +- (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { + // Invoking this method without a completedBlock is pointless + NSParameterAssert(completedBlock); + + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + if ([url isKindOfClass:NSString.class]) { + url = [NSURL URLWithString:(NSString *)url]; + } + + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) { + url = nil; + } + + __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; + __weak SDWebImageCombinedOperation *weakOperation = operation; + + BOOL isFailedUrl = NO; + @synchronized (self.failedURLs) { + isFailedUrl = [self.failedURLs containsObject:url]; + } + + if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { + dispatch_main_sync_safe(^{ + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; + completedBlock(nil, error, SDImageCacheTypeNone, YES); + }); + return operation; + } + + @synchronized (self.runningOperations) { + [self.runningOperations addObject:operation]; + } + NSString *key = [self cacheKeyForURL:url]; + + operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { + if (operation.isCancelled) { + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + + return; + } + + if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { + if (image && options & SDWebImageRefreshCached) { + dispatch_main_sync_safe(^{ + // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image + // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. + completedBlock(image, nil, cacheType, YES); + }); + } + + // download if no image or requested to refresh anyway, and download allowed by delegate + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; + if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; + if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; + if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; + if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; + if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; + if (image && options & SDWebImageRefreshCached) { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { + if (weakOperation.isCancelled) { + dispatch_main_sync_safe(^{ + completedBlock(nil, nil, SDImageCacheTypeNone, finished); + }); + } + else if (error) { + dispatch_main_sync_safe(^{ + completedBlock(nil, error, SDImageCacheTypeNone, finished); + }); + + if (error.code != NSURLErrorNotConnectedToInternet) { + @synchronized (self.failedURLs) { + [self.failedURLs addObject:url]; + } + } + } + else { + BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); + + if (options & SDWebImageRefreshCached && image && !downloadedImage) { + // Image refresh hit the NSURLCache cache, do not call the completion block + } + // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it + else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; + + dispatch_main_sync_safe(^{ + completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished); + }); + + if (transformedImage && finished) { + BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; + [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk]; + } + }); + } + else { + dispatch_main_sync_safe(^{ + completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished); + }); + + if (downloadedImage && finished) { + [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; + } + } + } + + if (finished) { + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + }]; + operation.cancelBlock = ^{ + [subOperation cancel]; + }; + } + else if (image) { + dispatch_main_sync_safe(^{ + completedBlock(image, nil, cacheType, YES); + }); + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + else { + // Image not in cache and download disallowed by delegate + dispatch_main_sync_safe(^{ + completedBlock(nil, nil, SDImageCacheTypeNone, YES); + }); + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + }]; + + return operation; +} + +- (void)cancelAll { + @synchronized (self.runningOperations) { + [self.runningOperations makeObjectsPerformSelector:@selector(cancel)]; + [self.runningOperations removeAllObjects]; + } +} + +- (BOOL)isRunning { + return self.runningOperations.count > 0; +} + +@end + +@implementation SDWebImageCombinedOperation + +- (void)setCancelBlock:(void (^)())cancelBlock { + if (self.isCancelled) { + if (cancelBlock) cancelBlock(); + } + else { + _cancelBlock = [cancelBlock copy]; + } +} + +- (void)cancel { + self.cancelled = YES; + if (self.cacheOperation) { + [self.cacheOperation cancel]; + self.cacheOperation = nil; + } + if (self.cancelBlock) { + self.cancelBlock(); + self.cancelBlock = nil; + } +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h new file mode 100644 index 0000000..71094ee --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h @@ -0,0 +1,15 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +@protocol SDWebImageOperation + +- (void)cancel; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h new file mode 100644 index 0000000..991602a --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1,87 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +@class SDWebImagePrefetcher; + +@protocol SDWebImagePrefetcherDelegate + +@optional + +/** + * Called when an image was prefetched. + * + * @param imagePrefetcher The current image prefetcher + * @param imageURL The image url that was prefetched + * @param finishedCount The total number of images that were prefetched + * @param totalCount The total number of images that need to be prefetched + */ +- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; + +/** + * Called when all images are prefetched. + * @param imagePrefetcher The current image prefetcher + * @param totalCount The total number of images that need to be prefetched + * @param skippedCount The total number of images that were skipped + */ +- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; + +@end + + +/** + * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. + */ +@interface SDWebImagePrefetcher : NSObject + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentDownloads; + +/** + * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. + */ +@property (nonatomic, assign) SDWebImageOptions options; + +@property (weak, nonatomic) id delegate; + +/** + * Return the global image prefetcher instance. + */ ++ (SDWebImagePrefetcher *)sharedImagePrefetcher; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + */ +- (void)prefetchURLs:(NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + * @param progressBlock block to be called when progress updates + * @param completionBlock block to be called when prefetching is completed + */ +- (void)prefetchURLs:(NSArray *)urls progress:(void (^)(NSUInteger, NSUInteger))progressBlock completed:(void (^)(NSUInteger, NSUInteger))completionBlock; + +/** + * Remove and cancel queued list + */ +- (void)cancelPrefetching; + + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m new file mode 100644 index 0000000..595a9a9 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m @@ -0,0 +1,138 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImagePrefetcher.h" + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic) SDWebImageManager *manager; +@property (strong, nonatomic) NSArray *prefetchURLs; +@property (assign, nonatomic) NSUInteger requestedCount; +@property (assign, nonatomic) NSUInteger skippedCount; +@property (assign, nonatomic) NSUInteger finishedCount; +@property (assign, nonatomic) NSTimeInterval startedTime; +@property (copy, nonatomic) void (^completionBlock)(NSUInteger, NSUInteger); +@property (copy, nonatomic) void (^progressBlock)(NSUInteger, NSUInteger); + +@end + +@implementation SDWebImagePrefetcher + ++ (SDWebImagePrefetcher *)sharedImagePrefetcher { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _manager = [SDWebImageManager new]; + _options = SDWebImageLowPriority; + self.maxConcurrentDownloads = 3; + } + return self; +} + +- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { + self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; +} + +- (NSUInteger)maxConcurrentDownloads { + return self.manager.imageDownloader.maxConcurrentDownloads; +} + +- (void)startPrefetchingAtIndex:(NSUInteger)index { + if (index >= self.prefetchURLs.count) return; + self.requestedCount++; + [self.manager downloadWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (!finished) return; + self.finishedCount++; + + if (image) { + if (self.progressBlock) { + self.progressBlock(self.finishedCount,[self.prefetchURLs count]); + } +#ifdef SD_VERBOSE + NSLog(@"Prefetched %d out of %d", self.finishedCount, self.prefetchURLs.count); +#endif + } + else { + if (self.progressBlock) { + self.progressBlock(self.finishedCount,[self.prefetchURLs count]); + } +#ifdef SD_VERBOSE + NSLog(@"Prefetched %d out of %d (Failed)", self.finishedCount, [self.prefetchURLs count]); +#endif + + // Add last failed + self.skippedCount++; + } + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { + [self.delegate imagePrefetcher:self + didPrefetchURL:self.prefetchURLs[index] + finishedCount:self.finishedCount + totalCount:self.prefetchURLs.count + ]; + } + + if (self.prefetchURLs.count > self.requestedCount) { + [self startPrefetchingAtIndex:self.requestedCount]; + } + else if (self.finishedCount + self.skippedCount == self.requestedCount) { + [self reportStatus]; + if (self.completionBlock) { + self.completionBlock(self.finishedCount, self.skippedCount); + self.completionBlock = nil; + } + } + }]; +} + +- (void)reportStatus { + NSUInteger total = [self.prefetchURLs count]; +#ifdef SD_VERBOSE + NSLog(@"Finished prefetching (%d successful, %d skipped, timeElasped %.2f)", total - self.skippedCount, self.skippedCount, CFAbsoluteTimeGetCurrent() - self.startedTime); +#endif + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { + [self.delegate imagePrefetcher:self + didFinishWithTotalCount:(total - self.skippedCount) + skippedCount:self.skippedCount + ]; + } +} + +- (void)prefetchURLs:(NSArray *)urls { + [self prefetchURLs:urls progress:nil completed:nil]; +} + +- (void)prefetchURLs:(NSArray *)urls progress:(void (^)(NSUInteger, NSUInteger))progressBlock completed:(void (^)(NSUInteger, NSUInteger))completionBlock { + [self cancelPrefetching]; // Prevent duplicate prefetch request + self.startedTime = CFAbsoluteTimeGetCurrent(); + self.prefetchURLs = urls; + self.completionBlock = completionBlock; + self.progressBlock = progressBlock; + + // Starts prefetching from the very first image on the list with the max allowed concurrency + NSUInteger listCount = self.prefetchURLs.count; + for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { + [self startPrefetchingAtIndex:i]; + } +} + +- (void)cancelPrefetching { + self.prefetchURLs = nil; + self.skippedCount = 0; + self.requestedCount = 0; + self.finishedCount = 0; + [self.manager cancelAll]; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h new file mode 100644 index 0000000..1f5d2c8 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h @@ -0,0 +1,179 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. + */ +@interface UIButton (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the backgroundImageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block object to be executed after the request operation + * completed. This block has no return value and takes three argument: the requested + * `UIImage` object, the `NSError` object describing error that occurred, and an + * `SDImageCacheType` enum describing the source of the image obtained from. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block object to be executed after the request operation + * completed. This block has no return value and takes three argument: the requested + * `UIImage` object, the `NSError` object describing error that occurred, and an + * `SDImageCacheType` enum describing the source of the image obtained from. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block object to be executed after the request operation + * completed. This block has no return value and takes three argument: the requested + * `UIImage` object, the `NSError` object describing error that occurred, and an + * `SDImageCacheType` enum describing the source of the image obtained from. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Cancel the current download + */ +- (void)cancelCurrentImageLoad; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m new file mode 100644 index 0000000..7f849e7 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m @@ -0,0 +1,114 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIButton+WebCache.h" +#import "objc/runtime.h" + +static char operationKey; + +@implementation UIButton (WebCache) + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { + [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self cancelCurrentImageLoad]; + + [self setImage:placeholder forState:state]; + + if (url) { + __weak UIButton *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIButton *sself = wself; + if (!sself) return; + if (image) { + [sself setImage:image forState:state]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType); + } + }); + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { + [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self cancelCurrentImageLoad]; + + [self setBackgroundImage:placeholder forState:state]; + + if (url) { + __weak UIButton *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIButton *sself = wself; + if (!sself) return; + if (image) { + [sself setBackgroundImage:image forState:state]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType); + } + }); + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + + +- (void)cancelCurrentImageLoad { + // Cancel in progress downloader from queue + id operation = objc_getAssociatedObject(self, &operationKey); + if (operation) { + [operation cancel]; + objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h new file mode 100755 index 0000000..084f424 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h @@ -0,0 +1,19 @@ +// +// UIImage+GIF.h +// LBGIFImage +// +// Created by Laurin Brandner on 06.01.12. +// Copyright (c) 2012 __MyCompanyName__. All rights reserved. +// + +#import + +@interface UIImage (GIF) + ++ (UIImage *)sd_animatedGIFNamed:(NSString *)name; + ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data; + +- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m new file mode 100755 index 0000000..f48d179 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m @@ -0,0 +1,158 @@ +// +// UIImage+GIF.m +// LBGIFImage +// +// Created by Laurin Brandner on 06.01.12. +// Copyright (c) 2012 __MyCompanyName__. All rights reserved. +// + +#import "UIImage+GIF.h" +#import + +@implementation UIImage (GIF) + ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data { + if (!data) { + return nil; + } + + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + + size_t count = CGImageSourceGetCount(source); + + UIImage *animatedImage; + + if (count <= 1) { + animatedImage = [[UIImage alloc] initWithData:data]; + } + else { + NSMutableArray *images = [NSMutableArray array]; + + NSTimeInterval duration = 0.0f; + + for (size_t i = 0; i < count; i++) { + CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); + + duration += [self frameDurationAtIndex:i source:source]; + + [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; + + CGImageRelease(image); + } + + if (!duration) { + duration = (1.0f / 10.0f) * count; + } + + animatedImage = [UIImage animatedImageWithImages:images duration:duration]; + } + + CFRelease(source); + + return animatedImage; +} + ++ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { + float frameDuration = 0.1f; + CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); + NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; + NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; + + NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; + if (delayTimeUnclampedProp) { + frameDuration = [delayTimeUnclampedProp floatValue]; + } + else { + + NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; + if (delayTimeProp) { + frameDuration = [delayTimeProp floatValue]; + } + } + + // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. + // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify + // a duration of <= 10 ms. See and + // for more information. + + if (frameDuration < 0.011f) { + frameDuration = 0.100f; + } + + CFRelease(cfFrameProperties); + return frameDuration; +} + ++ (UIImage *)sd_animatedGIFNamed:(NSString *)name { + CGFloat scale = [UIScreen mainScreen].scale; + + if (scale > 1.0f) { + NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; + + NSData *data = [NSData dataWithContentsOfFile:retinaPath]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; + + data = [NSData dataWithContentsOfFile:path]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + return [UIImage imageNamed:name]; + } + else { + NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; + + NSData *data = [NSData dataWithContentsOfFile:path]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + return [UIImage imageNamed:name]; + } +} + +- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { + if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { + return self; + } + + CGSize scaledSize = size; + CGPoint thumbnailPoint = CGPointZero; + + CGFloat widthFactor = size.width / self.size.width; + CGFloat heightFactor = size.height / self.size.height; + CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; + scaledSize.width = self.size.width * scaleFactor; + scaledSize.height = self.size.height * scaleFactor; + + if (widthFactor > heightFactor) { + thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; + } + else if (widthFactor < heightFactor) { + thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; + } + + NSMutableArray *scaledImages = [NSMutableArray array]; + + UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); + + for (UIImage *image in self.images) { + [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; + UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); + + [scaledImages addObject:newImage]; + } + + UIGraphicsEndImageContext(); + + return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h new file mode 100644 index 0000000..186ebc0 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h @@ -0,0 +1,15 @@ +// +// UIImage+MultiFormat.h +// SDWebImage +// +// Created by Olivier Poitrey on 07/06/13. +// Copyright (c) 2013 Dailymotion. All rights reserved. +// + +#import + +@interface UIImage (MultiFormat) + ++ (UIImage *)sd_imageWithData:(NSData *)data; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m new file mode 100644 index 0000000..e2e3e80 --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m @@ -0,0 +1,39 @@ +// +// UIImage+MultiFormat.m +// SDWebImage +// +// Created by Olivier Poitrey on 07/06/13. +// Copyright (c) 2013 Dailymotion. All rights reserved. +// + +#import "UIImage+MultiFormat.h" +#import "UIImage+GIF.h" +#import "NSData+ImageContentType.h" + +#ifdef SD_WEBP +#import "UIImage+WebP.h" +#endif + +@implementation UIImage (MultiFormat) + ++ (UIImage *)sd_imageWithData:(NSData *)data { + UIImage *image; + NSString *imageContentType = [NSData contentTypeForImageData:data]; + if ([imageContentType isEqualToString:@"image/gif"]) { + image = [UIImage sd_animatedGIFWithData:data]; + } +#ifdef SD_WEBP + else if ([imageContentType isEqualToString:@"image/webp"]) + { + image = [UIImage sd_imageWithWebPData:data]; + } +#endif + else { + image = [[UIImage alloc] initWithData:data]; + } + + + return image; +} + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h new file mode 100644 index 0000000..46f1f0b --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1,150 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + * + * Usage with a UITableViewCell sub-class: + * + * @code + +#import + +... + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *MyIdentifier = @"MyIdentifier"; + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + + if (cell == nil) { + cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] + autorelease]; + } + + // Here we use the provided setImageWithURL: method to load the web image + // Ensure you use a placeholder image otherwise cells will be initialized with no image + [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder"]]; + + cell.textLabel.text = @"My Text"; + return cell; +} + + * @endcode + */ +@interface UIImageView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Download an array of images and starts them in an animation loop + * + *@param arrayOfURLs An array of NSURL + */ +- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; + +/** + * Cancel the current download + */ +- (void)cancelCurrentImageLoad; + +- (void)cancelCurrentArrayLoad; + +@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m new file mode 100644 index 0000000..ed65a0e --- /dev/null +++ b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m @@ -0,0 +1,116 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+WebCache.h" +#import "objc/runtime.h" + +static char operationKey; +static char operationArrayKey; + +@implementation UIImageView (WebCache) + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { + [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { + [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { + [self cancelCurrentImageLoad]; + + self.image = placeholder; + + if (url) { + __weak UIImageView *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (!wself) return; + dispatch_main_sync_safe(^{ + if (!wself) return; + if (image) { + wself.image = image; + [wself setNeedsLayout]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType); + } + }); + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { + [self cancelCurrentArrayLoad]; + __weak UIImageView *wself = self; + + NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; + + for (NSURL *logoImageURL in arrayOfURLs) { + id operation = [SDWebImageManager.sharedManager downloadWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIImageView *sself = wself; + [sself stopAnimating]; + if (sself && image) { + NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; + if (!currentImages) { + currentImages = [[NSMutableArray alloc] init]; + } + [currentImages addObject:image]; + + sself.animationImages = currentImages; + [sself setNeedsLayout]; + } + [sself startAnimating]; + }); + }]; + [operationsArray addObject:operation]; + } + + objc_setAssociatedObject(self, &operationArrayKey, [NSArray arrayWithArray:operationsArray], OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)cancelCurrentImageLoad { + // Cancel in progress downloader from queue + id operation = objc_getAssociatedObject(self, &operationKey); + if (operation) { + [operation cancel]; + objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)cancelCurrentArrayLoad { + // Cancel in progress downloader from queue + NSArray *operations = objc_getAssociatedObject(self, &operationArrayKey); + for (id operation in operations) { + if (operation) { + [operation cancel]; + } + } + objc_setAssociatedObject(self, &operationArrayKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/Source/JTSImageViewController.h b/Source/JTSImageViewController.h index e2e3b1d..a8fa642 100644 --- a/Source/JTSImageViewController.h +++ b/Source/JTSImageViewController.h @@ -89,6 +89,29 @@ extern CGFloat const JTSImageViewController_DefaultBackgroundBlurRadius; mode:(JTSImageViewControllerMode)mode backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle; +/** + Initializer for using JTSImageViewController with a custom image downloader for the purpose of easily allowing cooperation with image caching 3rd party libraries like SDWebImage. + + @param imageInfo The source info for image and transition metadata. Required. + + @param mode The mode to be used. (JTSImageViewController has an alternate alt text mode). Required. + + @param backgroundStyle Currently, either scaled-and-dimmed, or scaled-dimmed-and-blurred. The latter is like Tweetbot 3.0's background style. + + @param customImageProgress Progress object to be updated by the caller with completed and totalUnitCount to inform of download progress. + */ +- (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo + mode:(JTSImageViewControllerMode)mode + backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle + customImageProgress:(NSProgress*)customImageProgress; + +/** + Image setter intended for use only when using custom image downloader to provide the UIImage to be used upon download/retrieval completion. + + @param customImage Full image to be displayed + */ +-(void)customImageSetter:(UIImage*)customImage; + /** JTSImageViewController is presented from viewController as a UIKit modal view controller. diff --git a/Source/JTSImageViewController.m b/Source/JTSImageViewController.m index 31c13fa..b7ceea8 100644 --- a/Source/JTSImageViewController.m +++ b/Source/JTSImageViewController.m @@ -53,6 +53,7 @@ @interface JTSImageViewController () @property (assign, nonatomic) BOOL isManuallyResizingTheScrollViewFrame; @property (assign, nonatomic) BOOL imageDownloadFailed; @property (assign, nonatomic) BOOL statusBarHiddenPriorToPresentation; +@property (assign, nonatomic) BOOL imageDownloadUsingCustom; @property (assign, nonatomic) CGRect startingReferenceFrameForThumbnail; @property (assign, nonatomic) CGRect startingReferenceFrameForThumbnailInPresentingViewControllersOriginalOrientation; @@ -86,6 +87,7 @@ @interface JTSImageViewController () @property (strong, nonatomic) NSURLSessionDataTask *imageDownloadDataTask; @property (strong, nonatomic) NSTimer *downloadProgressTimer; +@property (strong, nonatomic) NSProgress * customImageProgress; @end @@ -117,6 +119,56 @@ - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo return self; } +- (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo + mode:(JTSImageViewControllerMode)mode + backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle + customImageProgress:(NSProgress*)customImageProgress{ + + self = [super initWithNibName:nil bundle:nil]; + if (self) { + _backgroundBlurRadius = JTSImageViewController_DefaultBackgroundBlurRadius; + _alphaForBackgroundDimmingOverlay = JTSImageViewController_DefaultAlphaForBackgroundDimmingOverlay; + _imageInfo = imageInfo; + _currentSnapshotRotationTransform = CGAffineTransformIdentity; + _mode = mode; + _backgroundStyle = backgroundStyle; + _accessibilityLabel = [self defaultAccessibilityLabelForScrollView]; + _accessibilityHintZoomedIn = [self defaultAccessibilityHintForScrollView:YES]; + _accessibilityHintZoomedOut = [self defaultAccessibilityHintForScrollView:NO]; + if (_mode == JTSImageViewControllerMode_Image) { + _imageDownloadUsingCustom = YES; + //set placeholder + [self setImage:imageInfo.placeholderImage]; + //caller is responsible for setting the image view via block + //progress timer will call progress completion block + _customImageProgress = customImageProgress; + [self startProgressTimer]; + } + } + return self; +} + +-(void)customImageSetter:(UIImage*)customImage{ + + NSParameterAssert(customImage); + + [self cancelProgressTimer]; + if (customImage) { + if (self.isViewLoaded) { + [self updateInterfaceWithImage:customImage]; + } else { + [self setImage:customImage]; + } + } else if (self.image == nil) { + [self setImageDownloadFailed:YES]; + if (self.isPresented && self.isAnimatingAPresentationOrDismissal == NO) { + [self dismiss:YES]; + } + // If we're still presenting, at the end of presentation, + // we'll auto dismiss. + } +} + - (void)showFromViewController:(UIViewController *)viewController transition:(JTSImageViewControllerTransition)transition { @@ -1552,14 +1604,27 @@ - (void)cancelProgressTimer { } - (void)progressTimerFired:(NSTimer *)timer { + CGFloat progress = 0; - CGFloat bytesExpected = self.imageDownloadDataTask.countOfBytesExpectedToReceive; - if (bytesExpected > 0 && _imageIsBeingReadFromDisk == NO) { - [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{ - self.spinner.alpha = 0; - self.progressView.alpha = 1; - } completion:nil]; - progress = self.imageDownloadDataTask.countOfBytesReceived / bytesExpected; + if(self.imageDownloadUsingCustom){ + if(self.customImageProgress){ + //use progress object to determine completion + progress = _customImageProgress.fractionCompleted; + if(_customImageProgress.totalUnitCount){ + self.spinner.alpha = 0; + self.progressView.alpha = 1; + } + } + } else { + //JTSSimpleImageDownloader + CGFloat bytesExpected = self.imageDownloadDataTask.countOfBytesExpectedToReceive; + if (bytesExpected > 0 && _imageIsBeingReadFromDisk == NO) { + [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{ + self.spinner.alpha = 0; + self.progressView.alpha = 1; + } completion:nil]; + progress = self.imageDownloadDataTask.countOfBytesReceived / bytesExpected; + } } [self.progressView setProgress:progress]; } From 311f275cfe589a49d9f31865ccac3d1f49e289cc Mon Sep 17 00:00:00 2001 From: Geoff MacDonald Date: Tue, 29 Apr 2014 12:45:25 -0400 Subject: [PATCH 2/3] consolidated image setting --- Source/JTSImageViewController.m | 52 +++++++++++++-------------------- 1 file changed, 21 insertions(+), 31 deletions(-) diff --git a/Source/JTSImageViewController.m b/Source/JTSImageViewController.m index b7ceea8..210fe02 100644 --- a/Source/JTSImageViewController.m +++ b/Source/JTSImageViewController.m @@ -150,22 +150,8 @@ - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo -(void)customImageSetter:(UIImage*)customImage{ - NSParameterAssert(customImage); - - [self cancelProgressTimer]; - if (customImage) { - if (self.isViewLoaded) { - [self updateInterfaceWithImage:customImage]; - } else { - [self setImage:customImage]; - } - } else if (self.image == nil) { - [self setImageDownloadFailed:YES]; - if (self.isPresented && self.isAnimatingAPresentationOrDismissal == NO) { - [self dismiss:YES]; - } - // If we're still presenting, at the end of presentation, - // we'll auto dismiss. + if(customImage && self.imageDownloadUsingCustom){ + [self downloadCompletion:customImage]; } } @@ -325,21 +311,7 @@ - (void)setupImageAndDownloadIfNecessary:(JTSImageInfo *)imageInfo { __weak JTSImageViewController *weakSelf = self; NSURLSessionDataTask *task = [JTSSimpleImageDownloader downloadImageForURL:imageInfo.imageURL canonicalURL:imageInfo.canonicalImageURL completion:^(UIImage *image) { - [weakSelf cancelProgressTimer]; - if (image) { - if (weakSelf.isViewLoaded) { - [weakSelf updateInterfaceWithImage:image]; - } else { - [weakSelf setImage:image]; - } - } else if (weakSelf.image == nil) { - [weakSelf setImageDownloadFailed:YES]; - if (weakSelf.isPresented && weakSelf.isAnimatingAPresentationOrDismissal == NO) { - [weakSelf dismiss:YES]; - } - // If we're still presenting, at the end of presentation, - // we'll auto dismiss. - } + [weakSelf downloadCompletion:image]; }]; [self setImageDownloadDataTask:task]; @@ -348,6 +320,24 @@ - (void)setupImageAndDownloadIfNecessary:(JTSImageInfo *)imageInfo { } } +-(void)downloadCompletion:(UIImage*)image{ + [self cancelProgressTimer]; + if (image) { + if (self.isViewLoaded) { + [self updateInterfaceWithImage:image]; + } else { + [self setImage:image]; + } + } else if (self.image == nil) { + [self setImageDownloadFailed:YES]; + if (self.isPresented && self.isAnimatingAPresentationOrDismissal == NO) { + [self dismiss:YES]; + } + // If we're still presenting, at the end of presentation, + // we'll auto dismiss. + } +} + - (void)_viewDidLoadForImageMode { [self.view setBackgroundColor:[UIColor blackColor]]; From 2fb9d82729cf592034b0b48fe2b9780b7b28f1ea Mon Sep 17 00:00:00 2001 From: Geoff MacDonald Date: Thu, 1 May 2014 12:03:46 -0400 Subject: [PATCH 3/3] more verbose methods, consolidated init, removed SDWebImage and replaced with NSURLSessionDownloadTask for clarity purposes --- .../JTSImageVC.xcodeproj/project.pbxproj | 82 --- .../xcshareddata/JTSImageVC.xccheckout | 14 +- .../JTSImageVC/JTSImageVC/JTSViewController.h | 2 +- .../JTSImageVC/JTSImageVC/JTSViewController.m | 56 +- .../SDWebImage/NSData+ImageContentType.h | 10 - .../SDWebImage/NSData+ImageContentType.m | 40 -- .../JTSImageVC/SDWebImage/SDImageCache.h | 187 ------- .../JTSImageVC/SDWebImage/SDImageCache.m | 500 ------------------ .../JTSImageVC/SDWebImage/SDWebImageCompat.h | 62 --- .../JTSImageVC/SDWebImage/SDWebImageCompat.m | 41 -- .../JTSImageVC/SDWebImage/SDWebImageDecoder.h | 18 - .../JTSImageVC/SDWebImage/SDWebImageDecoder.m | 72 --- .../SDWebImage/SDWebImageDownloader.h | 151 ------ .../SDWebImage/SDWebImageDownloader.m | 215 -------- .../SDWebImageDownloaderOperation.h | 24 - .../SDWebImageDownloaderOperation.m | 397 -------------- .../JTSImageVC/SDWebImage/SDWebImageManager.h | 205 ------- .../JTSImageVC/SDWebImage/SDWebImageManager.m | 254 --------- .../SDWebImage/SDWebImageOperation.h | 15 - .../SDWebImage/SDWebImagePrefetcher.h | 87 --- .../SDWebImage/SDWebImagePrefetcher.m | 138 ----- .../JTSImageVC/SDWebImage/UIButton+WebCache.h | 179 ------- .../JTSImageVC/SDWebImage/UIButton+WebCache.m | 114 ---- .../JTSImageVC/SDWebImage/UIImage+GIF.h | 19 - .../JTSImageVC/SDWebImage/UIImage+GIF.m | 158 ------ .../SDWebImage/UIImage+MultiFormat.h | 15 - .../SDWebImage/UIImage+MultiFormat.m | 39 -- .../SDWebImage/UIImageView+WebCache.h | 150 ------ .../SDWebImage/UIImageView+WebCache.m | 116 ---- Source/JTSImageViewController.h | 8 +- Source/JTSImageViewController.m | 45 +- 31 files changed, 68 insertions(+), 3345 deletions(-) delete mode 100644 Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDImageCache.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDImageCache.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m delete mode 100755 Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h delete mode 100755 Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h delete mode 100644 Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m diff --git a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj index ef3cfaa..603e98d 100644 --- a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj +++ b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.pbxproj @@ -28,18 +28,6 @@ 7F9A794218E75712000CAA69 /* UIImage+JTSImageEffects.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F9A794118E75712000CAA69 /* UIImage+JTSImageEffects.m */; }; 7FE0848218E7C5C600F2F6B4 /* banecat.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 7FE0848118E7C5C600F2F6B4 /* banecat.jpg */; }; 7FE95B4E18EE0E8100F18370 /* UIApplication+JTSImageViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FE95B4D18EE0E8100F18370 /* UIApplication+JTSImageViewController.m */; }; - C30DCC4B191001B500B8445C /* NSData+ImageContentType.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC33191001B500B8445C /* NSData+ImageContentType.m */; }; - C30DCC4C191001B500B8445C /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC35191001B500B8445C /* SDImageCache.m */; }; - C30DCC4D191001B500B8445C /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC37191001B500B8445C /* SDWebImageCompat.m */; }; - C30DCC4E191001B500B8445C /* SDWebImageDecoder.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC39191001B500B8445C /* SDWebImageDecoder.m */; }; - C30DCC4F191001B500B8445C /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */; }; - C30DCC50191001B500B8445C /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */; }; - C30DCC51191001B500B8445C /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC3F191001B500B8445C /* SDWebImageManager.m */; }; - C30DCC52191001B500B8445C /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */; }; - C30DCC53191001B500B8445C /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC44191001B500B8445C /* UIButton+WebCache.m */; }; - C30DCC54191001B500B8445C /* UIImage+GIF.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC46191001B500B8445C /* UIImage+GIF.m */; }; - C30DCC55191001B500B8445C /* UIImage+MultiFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */; }; - C30DCC56191001B500B8445C /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */; }; C30DCC58191007E900B8445C /* jimpam.gif in Resources */ = {isa = PBXBuildFile; fileRef = C30DCC57191007E900B8445C /* jimpam.gif */; }; /* End PBXBuildFile section */ @@ -86,31 +74,6 @@ 7FE0848118E7C5C600F2F6B4 /* banecat.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = banecat.jpg; sourceTree = ""; }; 7FE95B4C18EE0E8100F18370 /* UIApplication+JTSImageViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIApplication+JTSImageViewController.h"; path = "../../../Source/UIApplication+JTSImageViewController.h"; sourceTree = ""; }; 7FE95B4D18EE0E8100F18370 /* UIApplication+JTSImageViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIApplication+JTSImageViewController.m"; path = "../../../Source/UIApplication+JTSImageViewController.m"; sourceTree = ""; }; - C30DCC32191001B500B8445C /* NSData+ImageContentType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+ImageContentType.h"; sourceTree = ""; }; - C30DCC33191001B500B8445C /* NSData+ImageContentType.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+ImageContentType.m"; sourceTree = ""; }; - C30DCC34191001B500B8445C /* SDImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDImageCache.h; sourceTree = ""; }; - C30DCC35191001B500B8445C /* SDImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDImageCache.m; sourceTree = ""; }; - C30DCC36191001B500B8445C /* SDWebImageCompat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageCompat.h; sourceTree = ""; }; - C30DCC37191001B500B8445C /* SDWebImageCompat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageCompat.m; sourceTree = ""; }; - C30DCC38191001B500B8445C /* SDWebImageDecoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDecoder.h; sourceTree = ""; }; - C30DCC39191001B500B8445C /* SDWebImageDecoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDecoder.m; sourceTree = ""; }; - C30DCC3A191001B500B8445C /* SDWebImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloader.h; sourceTree = ""; }; - C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloader.m; sourceTree = ""; }; - C30DCC3C191001B500B8445C /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloaderOperation.h; sourceTree = ""; }; - C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloaderOperation.m; sourceTree = ""; }; - C30DCC3E191001B500B8445C /* SDWebImageManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageManager.h; sourceTree = ""; }; - C30DCC3F191001B500B8445C /* SDWebImageManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageManager.m; sourceTree = ""; }; - C30DCC40191001B500B8445C /* SDWebImageOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageOperation.h; sourceTree = ""; }; - C30DCC41191001B500B8445C /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImagePrefetcher.h; sourceTree = ""; }; - C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImagePrefetcher.m; sourceTree = ""; }; - C30DCC43191001B500B8445C /* UIButton+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+WebCache.h"; sourceTree = ""; }; - C30DCC44191001B500B8445C /* UIButton+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+WebCache.m"; sourceTree = ""; }; - C30DCC45191001B500B8445C /* UIImage+GIF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+GIF.h"; sourceTree = ""; }; - C30DCC46191001B500B8445C /* UIImage+GIF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+GIF.m"; sourceTree = ""; }; - C30DCC47191001B500B8445C /* UIImage+MultiFormat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+MultiFormat.h"; sourceTree = ""; }; - C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+MultiFormat.m"; sourceTree = ""; }; - C30DCC49191001B500B8445C /* UIImageView+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+WebCache.h"; sourceTree = ""; }; - C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+WebCache.m"; sourceTree = ""; }; C30DCC57191007E900B8445C /* jimpam.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = jimpam.gif; sourceTree = ""; }; /* End PBXFileReference section */ @@ -141,7 +104,6 @@ 7F9A78F218E754A7000CAA69 = { isa = PBXGroup; children = ( - C30DCC31191001B500B8445C /* SDWebImage */, 7F9A793318E754D9000CAA69 /* Source */, 7F9A790418E754A7000CAA69 /* Sample App */, 7F9A792318E754A7000CAA69 /* Sample App Tests */, @@ -237,38 +199,6 @@ path = JTSImageVC; sourceTree = ""; }; - C30DCC31191001B500B8445C /* SDWebImage */ = { - isa = PBXGroup; - children = ( - C30DCC32191001B500B8445C /* NSData+ImageContentType.h */, - C30DCC33191001B500B8445C /* NSData+ImageContentType.m */, - C30DCC34191001B500B8445C /* SDImageCache.h */, - C30DCC35191001B500B8445C /* SDImageCache.m */, - C30DCC36191001B500B8445C /* SDWebImageCompat.h */, - C30DCC37191001B500B8445C /* SDWebImageCompat.m */, - C30DCC38191001B500B8445C /* SDWebImageDecoder.h */, - C30DCC39191001B500B8445C /* SDWebImageDecoder.m */, - C30DCC3A191001B500B8445C /* SDWebImageDownloader.h */, - C30DCC3B191001B500B8445C /* SDWebImageDownloader.m */, - C30DCC3C191001B500B8445C /* SDWebImageDownloaderOperation.h */, - C30DCC3D191001B500B8445C /* SDWebImageDownloaderOperation.m */, - C30DCC3E191001B500B8445C /* SDWebImageManager.h */, - C30DCC3F191001B500B8445C /* SDWebImageManager.m */, - C30DCC40191001B500B8445C /* SDWebImageOperation.h */, - C30DCC41191001B500B8445C /* SDWebImagePrefetcher.h */, - C30DCC42191001B500B8445C /* SDWebImagePrefetcher.m */, - C30DCC43191001B500B8445C /* UIButton+WebCache.h */, - C30DCC44191001B500B8445C /* UIButton+WebCache.m */, - C30DCC45191001B500B8445C /* UIImage+GIF.h */, - C30DCC46191001B500B8445C /* UIImage+GIF.m */, - C30DCC47191001B500B8445C /* UIImage+MultiFormat.h */, - C30DCC48191001B500B8445C /* UIImage+MultiFormat.m */, - C30DCC49191001B500B8445C /* UIImageView+WebCache.h */, - C30DCC4A191001B500B8445C /* UIImageView+WebCache.m */, - ); - path = SDWebImage; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -369,26 +299,14 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C30DCC4E191001B500B8445C /* SDWebImageDecoder.m in Sources */, - C30DCC51191001B500B8445C /* SDWebImageManager.m in Sources */, - C30DCC4B191001B500B8445C /* NSData+ImageContentType.m in Sources */, - C30DCC4D191001B500B8445C /* SDWebImageCompat.m in Sources */, 7F9A793918E75558000CAA69 /* JTSImageInfo.m in Sources */, 7FE95B4E18EE0E8100F18370 /* UIApplication+JTSImageViewController.m in Sources */, 7F9A791518E754A7000CAA69 /* JTSViewController.m in Sources */, - C30DCC53191001B500B8445C /* UIButton+WebCache.m in Sources */, - C30DCC52191001B500B8445C /* SDWebImagePrefetcher.m in Sources */, - C30DCC50191001B500B8445C /* SDWebImageDownloaderOperation.m in Sources */, 7F9A793C18E75593000CAA69 /* JTSSimpleImageDownloader.m in Sources */, - C30DCC56191001B500B8445C /* UIImageView+WebCache.m in Sources */, 7F9A790F18E754A7000CAA69 /* JTSAppDelegate.m in Sources */, - C30DCC55191001B500B8445C /* UIImage+MultiFormat.m in Sources */, 7F9A794218E75712000CAA69 /* UIImage+JTSImageEffects.m in Sources */, - C30DCC4C191001B500B8445C /* SDImageCache.m in Sources */, 7F9A793F18E755F6000CAA69 /* JTSAnimatedGIFUtility.m in Sources */, 7F9A793618E75541000CAA69 /* JTSImageViewController.m in Sources */, - C30DCC54191001B500B8445C /* UIImage+GIF.m in Sources */, - C30DCC4F191001B500B8445C /* SDWebImageDownloader.m in Sources */, 7F9A790B18E754A7000CAA69 /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.xcworkspace/xcshareddata/JTSImageVC.xccheckout b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.xcworkspace/xcshareddata/JTSImageVC.xccheckout index 39850e4..362ba8e 100644 --- a/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.xcworkspace/xcshareddata/JTSImageVC.xccheckout +++ b/Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.xcworkspace/xcshareddata/JTSImageVC.xccheckout @@ -5,34 +5,34 @@ IDESourceControlProjectFavoriteDictionaryKey IDESourceControlProjectIdentifier - 72F2EE3C-784A-4F2D-BAF4-70F79770BA55 + A53BEEAD-1C96-4AD9-B9A4-DD2DC3EE505A IDESourceControlProjectName JTSImageVC IDESourceControlProjectOriginsDictionary - 8B8BC593-E728-4EBC-BBF3-007F30B195CC - ssh://github.com/jaredsinclair/JTSImageViewController.git + F5D39521-8FA9-4276-82BE-B055A2EDD9D3 + https://github.com/geoffmacd/JTSImageViewController.git IDESourceControlProjectPath Sample App/JTSImageVC/JTSImageVC.xcodeproj/project.xcworkspace IDESourceControlProjectRelativeInstallPathDictionary - 8B8BC593-E728-4EBC-BBF3-007F30B195CC + F5D39521-8FA9-4276-82BE-B055A2EDD9D3 ../../../.. IDESourceControlProjectURL - ssh://github.com/jaredsinclair/JTSImageViewController.git + https://github.com/geoffmacd/JTSImageViewController.git IDESourceControlProjectVersion 110 IDESourceControlProjectWCCIdentifier - 8B8BC593-E728-4EBC-BBF3-007F30B195CC + F5D39521-8FA9-4276-82BE-B055A2EDD9D3 IDESourceControlProjectWCConfigurations IDESourceControlRepositoryExtensionIdentifierKey public.vcs.git IDESourceControlWCCIdentifierKey - 8B8BC593-E728-4EBC-BBF3-007F30B195CC + F5D39521-8FA9-4276-82BE-B055A2EDD9D3 IDESourceControlWCCName JTSImageViewController diff --git a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h index b5ffcf0..13df2a9 100644 --- a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h +++ b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.h @@ -8,7 +8,7 @@ #import -@interface JTSViewController : UIViewController +@interface JTSViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *bigImageButton; @property (weak, nonatomic) IBOutlet UIButton *simpleImageButton; diff --git a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m index afd5ea8..366e7d7 100644 --- a/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m +++ b/Sample App/JTSImageVC/JTSImageVC/JTSViewController.m @@ -10,13 +10,16 @@ #import "JTSImageViewController.h" #import "JTSImageInfo.h" - -#import "SDWebImageManager.h" +#import "JTSAnimatedGIFUtility.h" @interface JTSViewController () +@property NSProgress *customProgress; +@property JTSImageViewController * imageViewerForCustomLoading; + @end + @implementation JTSViewController - (void)viewDidLoad { @@ -75,38 +78,47 @@ - (IBAction)customBigButtonTapped:(id)sender { imageInfo.referenceRect = self.customBigImageButton.frame; imageInfo.referenceView = self.customBigImageButton.superview; - SDWebImageManager * manage= [SDWebImageManager sharedManager]; - //clear memory to test progress - SDImageCache *imageCache = [SDImageCache sharedImageCache]; - [imageCache clearMemory]; - [imageCache clearDisk]; - [imageCache cleanDisk]; - - __block NSProgress * progress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; - - SDWebImageDownloaderProgressBlock sdBlock = ^(NSInteger receivedSize, NSInteger expectedSize) { - - [progress setCompletedUnitCount:receivedSize]; - [progress setTotalUnitCount:expectedSize]; - }; + NSProgress * customProgress = [NSProgress progressWithTotalUnitCount:0]; + customProgress.kind = NSProgressKindFile; + self.customProgress = customProgress; //with custom progress JTSImageViewController *imageViewer = [[JTSImageViewController alloc] initWithImageInfo:imageInfo mode:JTSImageViewControllerMode_Image backgroundStyle:JTSImageViewControllerBackgroundStyle_ScaledDimmedBlurred - customImageProgress:progress]; + customImageLoadingProgress:self.customProgress]; + NSURLSessionConfiguration * sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + [sessionConfig setRequestCachePolicy:NSURLRequestReloadIgnoringCacheData];//no cache to allow repeatable testing + NSURLSession * session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //main thread response for delegates + NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://i.imgur.com/iGRxQNb.gif"]]]; - //hopefully url does not disappear - [manage downloadWithURL:[NSURL URLWithString:@"http://i.imgur.com/iGRxQNb.gif"] options:0 progress:sdBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - - [imageViewer customImageSetter:image]; - }]; + self.imageViewerForCustomLoading = imageViewer; + [task resume]; // Present the view controller. [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition]; } +#pragma mark - url session download delegate +-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{ + + _customProgress.totalUnitCount = expectedTotalBytes; + _customProgress.completedUnitCount = 0; + +} + +-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ + + _customProgress.totalUnitCount = totalBytesExpectedToWrite; + _customProgress.completedUnitCount = totalBytesWritten; +} + +-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ + + UIImage * image = [JTSAnimatedGIFUtility animatedImageWithAnimatedGIFURL:location]; + [self.imageViewerForCustomLoading customImageLoadingDidFinish:image]; +} @end diff --git a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h deleted file mode 100644 index bb78bb0..0000000 --- a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.h +++ /dev/null @@ -1,10 +0,0 @@ -// -// Created by Fabrice Aneche on 06/01/14. -// Copyright (c) 2014 Dailymotion. All rights reserved. -// - -#import - -@interface NSData (ImageContentType) -+ (NSString *)contentTypeForImageData:(NSData *)data; -@end diff --git a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m b/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m deleted file mode 100644 index 6fb352d..0000000 --- a/Sample App/JTSImageVC/SDWebImage/NSData+ImageContentType.m +++ /dev/null @@ -1,40 +0,0 @@ -// -// Created by Fabrice Aneche on 06/01/14. -// Copyright (c) 2014 Dailymotion. All rights reserved. -// - -#import "NSData+ImageContentType.h" - - -@implementation NSData (ImageContentType) - -+ (NSString *)contentTypeForImageData:(NSData *)data { - uint8_t c; - [data getBytes:&c length:1]; - switch (c) { - case 0xFF: - return @"image/jpeg"; - case 0x89: - return @"image/png"; - case 0x47: - return @"image/gif"; - case 0x49: - case 0x4D: - return @"image/tiff"; - case 0x52: - // R as RIFF for WEBP - if ([data length] < 12) { - return nil; - } - - NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; - if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { - return @"image/webp"; - } - - return nil; - } - return nil; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDImageCache.h b/Sample App/JTSImageVC/SDWebImage/SDImageCache.h deleted file mode 100644 index 2e1eed5..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDImageCache.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import -#import "SDWebImageCompat.h" - -typedef NS_ENUM(NSInteger, SDImageCacheType) { - /** - * The image wasn't available the SDWebImage caches, but was downloaded from the web. - */ - SDImageCacheTypeNone, - /** - * The image was obtained from the disk cache. - */ - SDImageCacheTypeDisk, - /** - * The image was obtained from the memory cache. - */ - SDImageCacheTypeMemory -}; - -typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); - -/** - * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed - * asynchronous so it doesn’t add unnecessary latency to the UI. - */ -@interface SDImageCache : NSObject - -/** - * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. - */ -@property (assign, nonatomic) NSUInteger maxMemoryCost; - -/** - * The maximum length of time to keep an image in the cache, in seconds - */ -@property (assign, nonatomic) NSInteger maxCacheAge; - -/** - * The maximum size of the cache, in bytes. - */ -@property (assign, nonatomic) NSUInteger maxCacheSize; - -/** - * Returns global shared cache instance - * - * @return SDImageCache global instance - */ -+ (SDImageCache *)sharedImageCache; - -/** - * Init a new cache store with a specific namespace - * - * @param ns The namespace to use for this cache store - */ -- (id)initWithNamespace:(NSString *)ns; - -/** - * Add a read-only cache path to search for images pre-cached by SDImageCache - * Useful if you want to bundle pre-loaded images with your app - * - * @param path The path to use for this read-only cache path - */ -- (void)addReadOnlyCachePath:(NSString *)path; - -/** - * Store an image into memory and disk cache at the given key. - * - * @param image The image to store - * @param key The unique image cache key, usually it's image absolute URL - */ -- (void)storeImage:(UIImage *)image forKey:(NSString *)key; - -/** - * Store an image into memory and optionally disk cache at the given key. - * - * @param image The image to store - * @param key The unique image cache key, usually it's image absolute URL - * @param toDisk Store the image to disk cache if YES - */ -- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; - -/** - * Store an image into memory and optionally disk cache at the given key. - * - * @param image The image to store - * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage - * @param imageData The image data as returned by the server, this representation will be used for disk storage - * instead of converting the given image object into a storable/compressed image format in order - * to save quality and CPU - * @param key The unique image cache key, usually it's image absolute URL - * @param toDisk Store the image to disk cache if YES - */ -- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; - -/** - * Query the disk cache asynchronously. - * - * @param key The unique key used to store the wanted image - */ -- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; - -/** - * Query the memory cache synchronously. - * - * @param key The unique key used to store the wanted image - */ -- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; - -/** - * Query the disk cache synchronously after checking the memory cache. - * - * @param key The unique key used to store the wanted image - */ -- (UIImage *)imageFromDiskCacheForKey:(NSString *)key; - -/** - * Remove the image from memory and disk cache synchronously - * - * @param key The unique image cache key - */ -- (void)removeImageForKey:(NSString *)key; - -/** - * Remove the image from memory and optionally disk cache synchronously - * - * @param key The unique image cache key - * @param fromDisk Also remove cache entry from disk if YES - */ -- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; - -/** - * Clear all memory cached images - */ -- (void)clearMemory; - -/** - * Clear all disk cached images. Non-blocking method - returns immediately. - * @param completionBlock An block that should be executed after cache expiration completes (optional) - */ -- (void)clearDiskOnCompletion:(void (^)())completion; - -/** - * Clear all disk cached images - * @see clearDiskOnCompletion: - */ -- (void)clearDisk; - -/** - * Remove all expired cached image from disk. Non-blocking method - returns immediately. - * @param completionBlock An block that should be executed after cache expiration completes (optional) - */ -- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock; - -/** - * Remove all expired cached image from disk - * @see cleanDiskWithCompletionBlock: - */ -- (void)cleanDisk; - -/** - * Get the size used by the disk cache - */ -- (NSUInteger)getSize; - -/** - * Get the number of images in the disk cache - */ -- (int)getDiskCount; - -/** - * Asynchronously calculate the disk cache's size. - */ -- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock; - -/** - * Check if image exists in cache already - */ -- (BOOL)diskImageExistsWithKey:(NSString *)key; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDImageCache.m b/Sample App/JTSImageVC/SDWebImage/SDImageCache.m deleted file mode 100644 index 3f36e5e..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDImageCache.m +++ /dev/null @@ -1,500 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDImageCache.h" -#import "SDWebImageDecoder.h" -#import "UIImage+MultiFormat.h" -#import - -static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week -// PNG signature bytes and data (below) -static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; -static NSData *kPNGSignatureData = nil; - -BOOL ImageDataHasPNGPreffix(NSData *data); - -BOOL ImageDataHasPNGPreffix(NSData *data) { - NSUInteger pngSignatureLength = [kPNGSignatureData length]; - if ([data length] >= pngSignatureLength) { - if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { - return YES; - } - } - - return NO; -} - -@interface SDImageCache () - -@property (strong, nonatomic) NSCache *memCache; -@property (strong, nonatomic) NSString *diskCachePath; -@property (strong, nonatomic) NSMutableArray *customPaths; -@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; - -@end - - -@implementation SDImageCache { - NSFileManager *_fileManager; -} - -+ (SDImageCache *)sharedImageCache { - static dispatch_once_t once; - static id instance; - dispatch_once(&once, ^{ - instance = [self new]; - kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; - }); - return instance; -} - -- (id)init { - return [self initWithNamespace:@"default"]; -} - -- (id)initWithNamespace:(NSString *)ns { - if ((self = [super init])) { - NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; - - // Create IO serial queue - _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); - - // Init default values - _maxCacheAge = kDefaultCacheMaxCacheAge; - - // Init the memory cache - _memCache = [[NSCache alloc] init]; - _memCache.name = fullNamespace; - - // Init the disk cache - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace]; - - dispatch_sync(_ioQueue, ^{ - _fileManager = [NSFileManager new]; - }); - -#if TARGET_OS_IPHONE - // Subscribe to app events - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(clearMemory) - name:UIApplicationDidReceiveMemoryWarningNotification - object:nil]; - - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(cleanDisk) - name:UIApplicationWillTerminateNotification - object:nil]; - - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(backgroundCleanDisk) - name:UIApplicationDidEnterBackgroundNotification - object:nil]; -#endif - } - - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - SDDispatchQueueRelease(_ioQueue); -} - -- (void)addReadOnlyCachePath:(NSString *)path { - if (!self.customPaths) { - self.customPaths = [NSMutableArray new]; - } - - if (![self.customPaths containsObject:path]) { - [self.customPaths addObject:path]; - } -} - -#pragma mark SDImageCache (private) - -- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { - NSString *filename = [self cachedFileNameForKey:key]; - return [path stringByAppendingPathComponent:filename]; -} - -- (NSString *)defaultCachePathForKey:(NSString *)key { - return [self cachePathForKey:key inPath:self.diskCachePath]; -} - -- (NSString *)cachedFileNameForKey:(NSString *)key { - const char *str = [key UTF8String]; - if (str == NULL) { - str = ""; - } - unsigned char r[CC_MD5_DIGEST_LENGTH]; - CC_MD5(str, (CC_LONG)strlen(str), r); - NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; - - return filename; -} - -#pragma mark ImageCache - -- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { - if (!image || !key) { - return; - } - - [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale]; - - if (toDisk) { - dispatch_async(self.ioQueue, ^{ - NSData *data = imageData; - - if (image && (recalculate || !data)) { -#if TARGET_OS_IPHONE - // We need to determine if the image is a PNG or a JPEG - // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) - // The first eight bytes of a PNG file always contain the following (decimal) values: - // 137 80 78 71 13 10 26 10 - - // We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly), - // we will consider it PNG to avoid loosing the transparency - BOOL imageIsPng = YES; - - // But if we have an image data, we will look at the preffix - if ([imageData length] >= [kPNGSignatureData length]) { - imageIsPng = ImageDataHasPNGPreffix(imageData); - } - - if (imageIsPng) { - data = UIImagePNGRepresentation(image); - } - else { - data = UIImageJPEGRepresentation(image, (CGFloat)1.0); - } -#else - data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; -#endif - } - - if (data) { - if (![_fileManager fileExistsAtPath:_diskCachePath]) { - [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; - } - - [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; - } - }); - } -} - -- (void)storeImage:(UIImage *)image forKey:(NSString *)key { - [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; -} - -- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { - [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; -} - -- (BOOL)diskImageExistsWithKey:(NSString *)key { - __block BOOL exists = NO; - dispatch_sync(_ioQueue, ^{ - exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; - }); - - return exists; -} - -- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { - return [self.memCache objectForKey:key]; -} - -- (UIImage *)imageFromDiskCacheForKey:(NSString *)key { - // First check the in-memory cache... - UIImage *image = [self imageFromMemoryCacheForKey:key]; - if (image) { - return image; - } - - // Second check the disk cache... - UIImage *diskImage = [self diskImageForKey:key]; - if (diskImage) { - CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; - [self.memCache setObject:diskImage forKey:key cost:cost]; - } - - return diskImage; -} - -- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { - NSString *defaultPath = [self defaultCachePathForKey:key]; - NSData *data = [NSData dataWithContentsOfFile:defaultPath]; - if (data) { - return data; - } - - for (NSString *path in self.customPaths) { - NSString *filePath = [self cachePathForKey:key inPath:path]; - NSData *imageData = [NSData dataWithContentsOfFile:filePath]; - if (imageData) { - return imageData; - } - } - - return nil; -} - -- (UIImage *)diskImageForKey:(NSString *)key { - NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; - if (data) { - UIImage *image = [UIImage sd_imageWithData:data]; - image = [self scaledImageForKey:key image:image]; - image = [UIImage decodedImageWithImage:image]; - return image; - } - else { - return nil; - } -} - -- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { - return SDScaledImageForKey(key, image); -} - -- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock { - NSOperation *operation = [NSOperation new]; - - if (!doneBlock) return nil; - - if (!key) { - doneBlock(nil, SDImageCacheTypeNone); - return nil; - } - - // First check the in-memory cache... - UIImage *image = [self imageFromMemoryCacheForKey:key]; - if (image) { - doneBlock(image, SDImageCacheTypeMemory); - return nil; - } - - dispatch_async(self.ioQueue, ^{ - if (operation.isCancelled) { - return; - } - - @autoreleasepool { - UIImage *diskImage = [self diskImageForKey:key]; - if (diskImage) { - CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; - [self.memCache setObject:diskImage forKey:key cost:cost]; - } - - dispatch_async(dispatch_get_main_queue(), ^{ - doneBlock(diskImage, SDImageCacheTypeDisk); - }); - } - }); - - return operation; -} - -- (void)removeImageForKey:(NSString *)key { - [self removeImageForKey:key fromDisk:YES]; -} - -- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { - if (key == nil) { - return; - } - - [self.memCache removeObjectForKey:key]; - - if (fromDisk) { - dispatch_async(self.ioQueue, ^{ - [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; - }); - } -} - -- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { - self.memCache.totalCostLimit = maxMemoryCost; -} - -- (NSUInteger)maxMemoryCost { - return self.memCache.totalCostLimit; -} - -- (void)clearMemory { - [self.memCache removeAllObjects]; -} - -- (void)clearDisk { - [self clearDiskOnCompletion:nil]; -} - -- (void)clearDiskOnCompletion:(void (^)())completion -{ - dispatch_async(self.ioQueue, ^{ - [_fileManager removeItemAtPath:self.diskCachePath error:nil]; - [_fileManager createDirectoryAtPath:self.diskCachePath - withIntermediateDirectories:YES - attributes:nil - error:NULL]; - - if (completion) { - dispatch_async(dispatch_get_main_queue(), ^{ - completion(); - }); - } - }); -} - -- (void)cleanDisk { - [self cleanDiskWithCompletionBlock:nil]; -} - -- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock { - dispatch_async(self.ioQueue, ^{ - NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; - NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; - - // This enumerator prefetches useful properties for our cache files. - NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL - includingPropertiesForKeys:resourceKeys - options:NSDirectoryEnumerationSkipsHiddenFiles - errorHandler:NULL]; - - NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; - NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; - NSUInteger currentCacheSize = 0; - - // Enumerate all of the files in the cache directory. This loop has two purposes: - // - // 1. Removing files that are older than the expiration date. - // 2. Storing file attributes for the size-based cleanup pass. - for (NSURL *fileURL in fileEnumerator) { - NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; - - // Skip directories. - if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { - continue; - } - - // Remove files that are older than the expiration date; - NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; - if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { - [_fileManager removeItemAtURL:fileURL error:nil]; - continue; - } - - // Store a reference to this file and account for its total size. - NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; - currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; - [cacheFiles setObject:resourceValues forKey:fileURL]; - } - - // If our remaining disk cache exceeds a configured maximum size, perform a second - // size-based cleanup pass. We delete the oldest files first. - if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { - // Target half of our maximum cache size for this cleanup pass. - const NSUInteger desiredCacheSize = self.maxCacheSize / 2; - - // Sort the remaining cache files by their last modification time (oldest first). - NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent - usingComparator:^NSComparisonResult(id obj1, id obj2) { - return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; - }]; - - // Delete files until we fall below our desired cache size. - for (NSURL *fileURL in sortedFiles) { - if ([_fileManager removeItemAtURL:fileURL error:nil]) { - NSDictionary *resourceValues = cacheFiles[fileURL]; - NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; - currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; - - if (currentCacheSize < desiredCacheSize) { - break; - } - } - } - } - if (completionBlock) { - dispatch_async(dispatch_get_main_queue(), ^{ - completionBlock(); - }); - } - }); -} - -- (void)backgroundCleanDisk { - UIApplication *application = [UIApplication sharedApplication]; - __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ - // Clean up any unfinished task business by marking where you - // stopped or ending the task outright. - [application endBackgroundTask:bgTask]; - bgTask = UIBackgroundTaskInvalid; - }]; - - // Start the long-running task and return immediately. - [self cleanDiskWithCompletionBlock:^{ - [application endBackgroundTask:bgTask]; - bgTask = UIBackgroundTaskInvalid; - }]; -} - -- (NSUInteger)getSize { - __block NSUInteger size = 0; - dispatch_sync(self.ioQueue, ^{ - NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; - for (NSString *fileName in fileEnumerator) { - NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; - NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; - size += [attrs fileSize]; - } - }); - return size; -} - -- (int)getDiskCount { - __block int count = 0; - dispatch_sync(self.ioQueue, ^{ - NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; - for (__unused NSString *fileName in fileEnumerator) { - count += 1; - } - }); - return count; -} - -- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock { - NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; - - dispatch_async(self.ioQueue, ^{ - NSUInteger fileCount = 0; - NSUInteger totalSize = 0; - - NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL - includingPropertiesForKeys:@[NSFileSize] - options:NSDirectoryEnumerationSkipsHiddenFiles - errorHandler:NULL]; - - for (NSURL *fileURL in fileEnumerator) { - NSNumber *fileSize; - [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; - totalSize += [fileSize unsignedIntegerValue]; - fileCount += 1; - } - - if (completionBlock) { - dispatch_async(dispatch_get_main_queue(), ^{ - completionBlock(fileCount, totalSize); - }); - } - }); -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h deleted file mode 100644 index 2d90d3c..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * (c) Jamie Pinkham - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import - -#ifdef __OBJC_GC__ -#error SDWebImage does not support Objective-C Garbage Collection -#endif - -#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 -#error SDWebImage doesn't support Deployement Target version < 5.0 -#endif - -#if !TARGET_OS_IPHONE -#import -#ifndef UIImage -#define UIImage NSImage -#endif -#ifndef UIImageView -#define UIImageView NSImageView -#endif -#else - -#import - -#endif - -#ifndef NS_ENUM -#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type -#endif - -#ifndef NS_OPTIONS -#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type -#endif - -#if OS_OBJECT_USE_OBJC - #undef SDDispatchQueueRelease - #undef SDDispatchQueueSetterSementics - #define SDDispatchQueueRelease(q) - #define SDDispatchQueueSetterSementics strong -#else -#undef SDDispatchQueueRelease -#undef SDDispatchQueueSetterSementics -#define SDDispatchQueueRelease(q) (dispatch_release(q)) -#define SDDispatchQueueSetterSementics assign -#endif - -extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); - -#define dispatch_main_sync_safe(block)\ - if ([NSThread isMainThread]) {\ - block();\ - }\ - else {\ - dispatch_sync(dispatch_get_main_queue(), block);\ - } diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m deleted file mode 100644 index 7f91153..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageCompat.m +++ /dev/null @@ -1,41 +0,0 @@ -// -// SDWebImageCompat.m -// SDWebImage -// -// Created by Olivier Poitrey on 11/12/12. -// Copyright (c) 2012 Dailymotion. All rights reserved. -// - -#import "SDWebImageCompat.h" - -#if !__has_feature(objc_arc) -#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag -#endif - -inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { - if ([image.images count] > 0) { - NSMutableArray *scaledImages = [NSMutableArray array]; - - for (UIImage *tempImage in image.images) { - [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; - } - - return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; - } - else { - if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { - CGFloat scale = 1.0; - if (key.length >= 8) { - // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) - NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; - if (range.location != NSNotFound) { - scale = 2.0; - } - } - - UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; - image = scaledImage; - } - return image; - } -} diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h deleted file mode 100644 index 0176a7b..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * Created by james on 9/28/11. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import -#import "SDWebImageCompat.h" - -@interface UIImage (ForceDecode) - -+ (UIImage *)decodedImageWithImage:(UIImage *)image; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m deleted file mode 100644 index 79ddb30..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDecoder.m +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * Created by james on 9/28/11. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageDecoder.h" - -@implementation UIImage (ForceDecode) - -+ (UIImage *)decodedImageWithImage:(UIImage *)image { - if (image.images) { - // Do not decode animated images - return image; - } - - CGImageRef imageRef = image.CGImage; - CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); - CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; - - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); - - int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); - BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || - infoMask == kCGImageAlphaNoneSkipFirst || - infoMask == kCGImageAlphaNoneSkipLast); - - // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. - // https://developer.apple.com/library/mac/#qa/qa1037/_index.html - if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { - // Unset the old alpha info. - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - - // Set noneSkipFirst. - bitmapInfo |= kCGImageAlphaNoneSkipFirst; - } - // Some PNGs tell us they have alpha but only 3 components. Odd. - else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { - // Unset the old alpha info. - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaPremultipliedFirst; - } - - // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. - CGContextRef context = CGBitmapContextCreate(NULL, - imageSize.width, - imageSize.height, - CGImageGetBitsPerComponent(imageRef), - 0, - colorSpace, - bitmapInfo); - CGColorSpaceRelease(colorSpace); - - // If failed, return undecompressed image - if (!context) return image; - - CGContextDrawImage(context, imageRect, imageRef); - CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); - - CGContextRelease(context); - - UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; - CGImageRelease(decompressedImageRef); - return decompressedImage; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h deleted file mode 100644 index 0895997..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import -#import "SDWebImageCompat.h" -#import "SDWebImageOperation.h" - -typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { - SDWebImageDownloaderLowPriority = 1 << 0, - SDWebImageDownloaderProgressiveDownload = 1 << 1, - - /** - * By default, request prevent the of NSURLCache. With this flag, NSURLCache - * is used with default policies. - */ - SDWebImageDownloaderUseNSURLCache = 1 << 2, - - /** - * Call completion block with nil image/imageData if the image was read from NSURLCache - * (to be combined with `SDWebImageDownloaderUseNSURLCache`). - */ - - SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, - /** - * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for - * extra time in background to let the request finish. If the background task expires the operation will be cancelled. - */ - - SDWebImageDownloaderContinueInBackground = 1 << 4, - - /** - * Handles cookies stored in NSHTTPCookieStore by setting - * NSMutableURLRequest.HTTPShouldHandleCookies = YES; - */ - SDWebImageDownloaderHandleCookies = 1 << 5, - - /** - * Enable to allow untrusted SSL ceriticates. - * Useful for testing purposes. Use with caution in production. - */ - SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, - - /** - * Put the image in the high priority queue. - */ - SDWebImageDownloaderHighPriority = 1 << 7, - - -}; - -typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { - /** - * Default value. All download operations will execute in queue style (first-in-first-out). - */ - SDWebImageDownloaderFIFOExecutionOrder, - - /** - * All download operations will execute in stack style (last-in-first-out). - */ - SDWebImageDownloaderLIFOExecutionOrder -}; - -extern NSString *const SDWebImageDownloadStartNotification; -extern NSString *const SDWebImageDownloadStopNotification; - -typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); - -typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); - -/** - * Asynchronous downloader dedicated and optimized for image loading. - */ -@interface SDWebImageDownloader : NSObject - -@property (assign, nonatomic) NSInteger maxConcurrentDownloads; - -/** - * Shows the current amount of downloads that still need to be downloaded - */ - -@property (readonly, nonatomic) NSUInteger currentDownloadCount; - - -/** - * The timeout value (in seconds) for the download operation. Default: 15.0. - */ -@property (assign, nonatomic) NSTimeInterval downloadTimeout; - - -/** - * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. - */ -@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; - -+ (SDWebImageDownloader *)sharedDownloader; - -/** - * Set filter to pick headers for downloading image HTTP request. - * - * This block will be invoked for each downloading image request, returned - * NSDictionary will be used as headers in corresponding HTTP request. - */ -@property (nonatomic, strong) NSDictionary *(^headersFilter)(NSURL *url, NSDictionary *headers); - -/** - * Set a value for a HTTP header to be appended to each download HTTP request. - * - * @param value The value for the header field. Use `nil` value to remove the header. - * @param field The name of the header field to set. - */ -- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; - -/** - * Returns the value of the specified HTTP header field. - * - * @return The value associated with the header field field, or `nil` if there is no corresponding header field. - */ -- (NSString *)valueForHTTPHeaderField:(NSString *)field; - -/** - * Creates a SDWebImageDownloader async downloader instance with a given URL - * - * The delegate will be informed when the image is finish downloaded or an error has happen. - * - * @see SDWebImageDownloaderDelegate - * - * @param url The URL to the image to download - * @param options The options to be used for this download - * @param progressBlock A block called repeatedly while the image is downloading - * @param completedBlock A block called once the download is completed. - * If the download succeeded, the image parameter is set, in case of error, - * error parameter is set with the error. The last parameter is always YES - * if SDWebImageDownloaderProgressiveDownload isn't use. With the - * SDWebImageDownloaderProgressiveDownload option, this block is called - * repeatedly with the partial image object and the finished argument set to NO - * before to be called a last time with the full image and finished argument - * set to YES. In case of error, the finished argument is always YES. - * - * @return A cancellable SDWebImageOperation - */ -- (id )downloadImageWithURL:(NSURL *)url - options:(SDWebImageDownloaderOptions)options - progress:(SDWebImageDownloaderProgressBlock)progressBlock - completed:(SDWebImageDownloaderCompletedBlock)completedBlock; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m deleted file mode 100644 index 5b7cae2..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloader.m +++ /dev/null @@ -1,215 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageDownloader.h" -#import "SDWebImageDownloaderOperation.h" -#import - -NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; -NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; - -static NSString *const kProgressCallbackKey = @"progress"; -static NSString *const kCompletedCallbackKey = @"completed"; - -@interface SDWebImageDownloader () - -@property (strong, nonatomic) NSOperationQueue *downloadQueue; -@property (weak, nonatomic) NSOperation *lastAddedOperation; -@property (strong, nonatomic) NSMutableDictionary *URLCallbacks; -@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; -// This queue is used to serialize the handling of the network responses of all the download operation in a single queue -@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; - -@end - -@implementation SDWebImageDownloader - -+ (void)initialize { - // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) - // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import - if (NSClassFromString(@"SDNetworkActivityIndicator")) { - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" - id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; -#pragma clang diagnostic pop - - // Remove observer in case it was previously added. - [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; - - [[NSNotificationCenter defaultCenter] addObserver:activityIndicator - selector:NSSelectorFromString(@"startActivity") - name:SDWebImageDownloadStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:activityIndicator - selector:NSSelectorFromString(@"stopActivity") - name:SDWebImageDownloadStopNotification object:nil]; - } -} - -+ (SDWebImageDownloader *)sharedDownloader { - static dispatch_once_t once; - static id instance; - dispatch_once(&once, ^{ - instance = [self new]; - }); - return instance; -} - -- (id)init { - if ((self = [super init])) { - _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; - _downloadQueue = [NSOperationQueue new]; - _downloadQueue.maxConcurrentOperationCount = 2; - _URLCallbacks = [NSMutableDictionary new]; - _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"]; - _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); - _downloadTimeout = 15.0; - } - return self; -} - -- (void)dealloc { - [self.downloadQueue cancelAllOperations]; - SDDispatchQueueRelease(_barrierQueue); -} - -- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { - if (value) { - self.HTTPHeaders[field] = value; - } - else { - [self.HTTPHeaders removeObjectForKey:field]; - } -} - -- (NSString *)valueForHTTPHeaderField:(NSString *)field { - return self.HTTPHeaders[field]; -} - -- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { - _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; -} - -- (NSUInteger)currentDownloadCount { - return _downloadQueue.operationCount; -} - -- (NSInteger)maxConcurrentDownloads { - return _downloadQueue.maxConcurrentOperationCount; -} - -- (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock { - __block SDWebImageDownloaderOperation *operation; - __weak SDWebImageDownloader *wself = self; - - [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ - NSTimeInterval timeoutInterval = wself.downloadTimeout; - if (timeoutInterval == 0.0) { - timeoutInterval = 15.0; - } - - // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise - NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; - request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); - request.HTTPShouldUsePipelining = YES; - if (wself.headersFilter) { - request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); - } - else { - request.allHTTPHeaderFields = wself.HTTPHeaders; - } - operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request - options:options - progress:^(NSInteger receivedSize, NSInteger expectedSize) { - if (!wself) return; - SDWebImageDownloader *sself = wself; - NSArray *callbacksForURL = [sself callbacksForURL:url]; - for (NSDictionary *callbacks in callbacksForURL) { - SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; - if (callback) callback(receivedSize, expectedSize); - } - } - completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { - if (!wself) return; - SDWebImageDownloader *sself = wself; - NSArray *callbacksForURL = [sself callbacksForURL:url]; - if (finished) { - [sself removeCallbacksForURL:url]; - } - for (NSDictionary *callbacks in callbacksForURL) { - SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; - if (callback) callback(image, data, error, finished); - } - } - cancelled:^{ - if (!wself) return; - SDWebImageDownloader *sself = wself; - [sself removeCallbacksForURL:url]; - }]; - - if (options & SDWebImageDownloaderHighPriority) { - operation.queuePriority = NSOperationQueuePriorityHigh; - } - - [wself.downloadQueue addOperation:operation]; - if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { - // Emulate LIFO execution order by systematically adding new operations as last operation's dependency - [wself.lastAddedOperation addDependency:operation]; - wself.lastAddedOperation = operation; - } - }]; - - return operation; -} - -- (void)addProgressCallback:(void (^)(NSInteger, NSInteger))progressBlock andCompletedBlock:(void (^)(UIImage *, NSData *data, NSError *, BOOL))completedBlock forURL:(NSURL *)url createCallback:(void (^)())createCallback { - // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. - if (url == nil) { - if (completedBlock != nil) { - completedBlock(nil, nil, nil, NO); - } - return; - } - - dispatch_barrier_sync(self.barrierQueue, ^{ - BOOL first = NO; - if (!self.URLCallbacks[url]) { - self.URLCallbacks[url] = [NSMutableArray new]; - first = YES; - } - - // Handle single download of simultaneous download request for the same URL - NSMutableArray *callbacksForURL = self.URLCallbacks[url]; - NSMutableDictionary *callbacks = [NSMutableDictionary new]; - if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; - if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; - [callbacksForURL addObject:callbacks]; - self.URLCallbacks[url] = callbacksForURL; - - if (first) { - createCallback(); - } - }); -} - -- (NSArray *)callbacksForURL:(NSURL *)url { - __block NSArray *callbacksForURL; - dispatch_sync(self.barrierQueue, ^{ - callbacksForURL = self.URLCallbacks[url]; - }); - return [callbacksForURL copy]; -} - -- (void)removeCallbacksForURL:(NSURL *)url { - dispatch_barrier_async(self.barrierQueue, ^{ - [self.URLCallbacks removeObjectForKey:url]; - }); -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h deleted file mode 100644 index 154a4e5..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import -#import "SDWebImageDownloader.h" -#import "SDWebImageOperation.h" - -@interface SDWebImageDownloaderOperation : NSOperation - -@property (strong, nonatomic, readonly) NSURLRequest *request; -@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; - -- (id)initWithRequest:(NSURLRequest *)request - options:(SDWebImageDownloaderOptions)options - progress:(SDWebImageDownloaderProgressBlock)progressBlock - completed:(SDWebImageDownloaderCompletedBlock)completedBlock - cancelled:(void (^)())cancelBlock; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m deleted file mode 100644 index 05783f8..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageDownloaderOperation.m +++ /dev/null @@ -1,397 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageDownloaderOperation.h" -#import "SDWebImageDecoder.h" -#import "UIImage+MultiFormat.h" -#import - -@interface SDWebImageDownloaderOperation () - -@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; -@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; -@property (copy, nonatomic) void (^cancelBlock)(); - -@property (assign, nonatomic, getter = isExecuting) BOOL executing; -@property (assign, nonatomic, getter = isFinished) BOOL finished; -@property (assign, nonatomic) NSInteger expectedSize; -@property (strong, nonatomic) NSMutableData *imageData; -@property (strong, nonatomic) NSURLConnection *connection; -@property (strong, atomic) NSThread *thread; - -#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 -@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; -#endif - -@end - -@implementation SDWebImageDownloaderOperation { - size_t width, height; - UIImageOrientation orientation; - BOOL responseFromCached; -} - -- (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock cancelled:(void (^)())cancelBlock { - if ((self = [super init])) { - _request = request; - _options = options; - _progressBlock = [progressBlock copy]; - _completedBlock = [completedBlock copy]; - _cancelBlock = [cancelBlock copy]; - _executing = NO; - _finished = NO; - _expectedSize = 0; - responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called - } - return self; -} - -- (void)start { - @synchronized (self) { - if (self.isCancelled) { - self.finished = YES; - [self reset]; - return; - } - -#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 - if ([self shouldContinueWhenAppEntersBackground]) { - __weak __typeof__ (self) wself = self; - self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof (wself) sself = wself; - - if (sself) { - [sself cancel]; - - [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId]; - sself.backgroundTaskId = UIBackgroundTaskInvalid; - } - }]; - } -#endif - - self.executing = YES; - self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; - self.thread = [NSThread currentThread]; - } - - [self.connection start]; - - if (self.connection) { - if (self.progressBlock) { - self.progressBlock(0, NSURLResponseUnknownLength); - } - [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; - - if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { - // Make sure to run the runloop in our background thread so it can process downloaded data - // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 - // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); - } - else { - CFRunLoopRun(); - } - - if (!self.isFinished) { - [self.connection cancel]; - [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; - } - } - else { - if (self.completedBlock) { - self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); - } - } - -#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 - if (self.backgroundTaskId != UIBackgroundTaskInvalid) { - [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; - self.backgroundTaskId = UIBackgroundTaskInvalid; - } -#endif -} - -- (void)cancel { - @synchronized (self) { - if (self.thread) { - [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; - } - else { - [self cancelInternal]; - } - } -} - -- (void)cancelInternalAndStop { - [self cancelInternal]; - CFRunLoopStop(CFRunLoopGetCurrent()); -} - -- (void)cancelInternal { - if (self.isFinished) return; - [super cancel]; - if (self.cancelBlock) self.cancelBlock(); - - if (self.connection) { - [self.connection cancel]; - [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; - - // As we cancelled the connection, its callback won't be called and thus won't - // maintain the isFinished and isExecuting flags. - if (self.isExecuting) self.executing = NO; - if (!self.isFinished) self.finished = YES; - } - - [self reset]; -} - -- (void)done { - self.finished = YES; - self.executing = NO; - [self reset]; -} - -- (void)reset { - self.cancelBlock = nil; - self.completedBlock = nil; - self.progressBlock = nil; - self.connection = nil; - self.imageData = nil; - self.thread = nil; -} - -- (void)setFinished:(BOOL)finished { - [self willChangeValueForKey:@"isFinished"]; - _finished = finished; - [self didChangeValueForKey:@"isFinished"]; -} - -- (void)setExecuting:(BOOL)executing { - [self willChangeValueForKey:@"isExecuting"]; - _executing = executing; - [self didChangeValueForKey:@"isExecuting"]; -} - -- (BOOL)isConcurrent { - return YES; -} - -#pragma mark NSURLConnection (delegate) - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { - if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) { - NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; - self.expectedSize = expected; - if (self.progressBlock) { - self.progressBlock(0, expected); - } - - self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; - } - else { - [self.connection cancel]; - - [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; - - if (self.completedBlock) { - self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); - } - - [self done]; - } -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { - [self.imageData appendData:data]; - - if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { - // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ - // Thanks to the author @Nyx0uf - - // Get the total bytes downloaded - const NSInteger totalSize = self.imageData.length; - - // Update the data source, we must pass ALL the data, not just the new bytes - CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL); - CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize); - - if (width + height == 0) { - CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); - if (properties) { - NSInteger orientationValue = -1; - CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); - if (val) CFNumberGetValue(val, kCFNumberLongType, &height); - val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); - if (val) CFNumberGetValue(val, kCFNumberLongType, &width); - val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); - if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); - CFRelease(properties); - - // When we draw to Core Graphics, we lose orientation information, - // which means the image below born of initWithCGIImage will be - // oriented incorrectly sometimes. (Unlike the image born of initWithData - // in connectionDidFinishLoading.) So save it here and pass it on later. - orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; - } - - } - - if (width + height > 0 && totalSize < self.expectedSize) { - // Create the image - CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); - -#ifdef TARGET_OS_IPHONE - // Workaround for iOS anamorphic image - if (partialImageRef) { - const size_t partialHeight = CGImageGetHeight(partialImageRef); - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); - CGColorSpaceRelease(colorSpace); - if (bmContext) { - CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); - CGImageRelease(partialImageRef); - partialImageRef = CGBitmapContextCreateImage(bmContext); - CGContextRelease(bmContext); - } - else { - CGImageRelease(partialImageRef); - partialImageRef = nil; - } - } -#endif - - if (partialImageRef) { - UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; - UIImage *scaledImage = [self scaledImageForKey:self.request.URL.absoluteString image:image]; - image = [UIImage decodedImageWithImage:scaledImage]; - CGImageRelease(partialImageRef); - dispatch_main_sync_safe(^{ - if (self.completedBlock) { - self.completedBlock(image, nil, nil, NO); - } - }); - } - } - - CFRelease(imageSource); - } - - if (self.progressBlock) { - self.progressBlock(self.imageData.length, self.expectedSize); - } -} - -+ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { - switch (value) { - case 1: - return UIImageOrientationUp; - case 3: - return UIImageOrientationDown; - case 8: - return UIImageOrientationLeft; - case 6: - return UIImageOrientationRight; - case 2: - return UIImageOrientationUpMirrored; - case 4: - return UIImageOrientationDownMirrored; - case 5: - return UIImageOrientationLeftMirrored; - case 7: - return UIImageOrientationRightMirrored; - default: - return UIImageOrientationUp; - } -} - -- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { - return SDScaledImageForKey(key, image); -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { - CFRunLoopStop(CFRunLoopGetCurrent()); - self.connection = nil; - - [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; - - SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; - - if (completionBlock) { - if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { - completionBlock(nil, nil, nil, YES); - self.completionBlock = nil; - [self done]; - } - else { - - UIImage *image = [UIImage sd_imageWithData:self.imageData]; - - image = [self scaledImageForKey:self.request.URL.absoluteString image:image]; - - if (!image.images) // Do not force decod animated GIFs - { - image = [UIImage decodedImageWithImage:image]; - } - - if (CGSizeEqualToSize(image.size, CGSizeZero)) { - completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); - } - else { - completionBlock(image, self.imageData, nil, YES); - } - self.completionBlock = nil; - [self done]; - } - } - else { - [self done]; - } -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - CFRunLoopStop(CFRunLoopGetCurrent()); - [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; - - if (self.completedBlock) { - self.completedBlock(nil, nil, error, YES); - } - - [self done]; -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { - responseFromCached = NO; // If this method is called, it means the response wasn't read from cache - if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { - // Prevents caching of responses - return nil; - } - else { - return cachedResponse; - } -} - -- (BOOL)shouldContinueWhenAppEntersBackground { - return self.options & SDWebImageDownloaderContinueInBackground; -} - -- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { - return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { - BOOL trustAllCertificates = (self.options & SDWebImageDownloaderAllowInvalidSSLCertificates); - if (trustAllCertificates && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] - forAuthenticationChallenge:challenge]; - } - - [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h deleted file mode 100644 index 45598c4..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageCompat.h" -#import "SDWebImageOperation.h" -#import "SDWebImageDownloader.h" -#import "SDImageCache.h" - -typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { - /** - * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. - * This flag disable this blacklisting. - */ - SDWebImageRetryFailed = 1 << 0, - - /** - * By default, image downloads are started during UI interactions, this flags disable this feature, - * leading to delayed download on UIScrollView deceleration for instance. - */ - SDWebImageLowPriority = 1 << 1, - - /** - * This flag disables on-disk caching - */ - SDWebImageCacheMemoryOnly = 1 << 2, - - /** - * This flag enables progressive download, the image is displayed progressively during download as a browser would do. - * By default, the image is only displayed once completely downloaded. - */ - SDWebImageProgressiveDownload = 1 << 3, - - /** - * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. - * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. - * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. - * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. - * - * Use this flag only if you can't make your URLs static with embeded cache busting parameter. - */ - SDWebImageRefreshCached = 1 << 4, - - /** - * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for - * extra time in background to let the request finish. If the background task expires the operation will be cancelled. - */ - SDWebImageContinueInBackground = 1 << 5, - - /** - * Handles cookies stored in NSHTTPCookieStore by setting - * NSMutableURLRequest.HTTPShouldHandleCookies = YES; - */ - SDWebImageHandleCookies = 1 << 6, - - /** - * Enable to allow untrusted SSL ceriticates. - * Useful for testing purposes. Use with caution in production. - */ - SDWebImageAllowInvalidSSLCertificates = 1 << 7, - - /** - * By default, image are loaded in the order they were queued. This flag move them to - * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which - * could take a while). - */ - SDWebImageHighPriority = 1 << 8 -}; - -typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType); - -typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished); - - -@class SDWebImageManager; - -@protocol SDWebImageManagerDelegate - -@optional - -/** - * Controls which image should be downloaded when the image is not found in the cache. - * - * @param imageManager The current `SDWebImageManager` - * @param imageURL The url of the image to be downloaded - * - * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. - */ -- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; - -/** - * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. - * NOTE: This method is called from a global queue in order to not to block the main thread. - * - * @param imageManager The current `SDWebImageManager` - * @param image The image to transform - * @param imageURL The url of the image to transform - * - * @return The transformed image object. - */ -- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; - -@end - -/** - * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. - * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). - * You can use this class directly to benefit from web image downloading with caching in another context than - * a UIView. - * - * Here is a simple example of how to use SDWebImageManager: - * - * @code - -SDWebImageManager *manager = [SDWebImageManager sharedManager]; -[manager downloadWithURL:imageURL - options:0 - progress:nil - completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (image) { - // do something with image - } - }]; - - * @endcode - */ -@interface SDWebImageManager : NSObject - -@property (weak, nonatomic) id delegate; - -@property (strong, nonatomic, readonly) SDImageCache *imageCache; -@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; - -/** - * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can - * be used to remove dynamic part of an image URL. - * - * The following example sets a filter in the application delegate that will remove any query-string from the - * URL before to use it as a cache key: - * - * @code - -[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { - url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; - return [url absoluteString]; -}]; - - * @endcode - */ -@property (strong) NSString *(^cacheKeyFilter)(NSURL *url); - -/** - * Returns global SDWebImageManager instance. - * - * @return SDWebImageManager shared instance - */ -+ (SDWebImageManager *)sharedManager; - -/** - * Downloads the image at the given URL if not present in cache or return the cached version otherwise. - * - * @param url The URL to the image - * @param options A mask to specify options to use for this request - * @param progressBlock A block called while image is downloading - * @param completedBlock A block called when operation has been completed. - * - * This parameter is required. - * - * This block has no return value and takes the requested UIImage as first parameter. - * In case of error the image parameter is nil and the second parameter may contain an NSError. - * - * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache - * or from the memory cache or from the network. - * - * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is - * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the - * block is called a last time with the full image and the last parameter set to YES. - * - * @return Returns a cancellable NSOperation - */ -- (id )downloadWithURL:(NSURL *)url - options:(SDWebImageOptions)options - progress:(SDWebImageDownloaderProgressBlock)progressBlock - completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; - -/** - * Cancel all current opreations - */ -- (void)cancelAll; - -/** - * Check one or more operations running - */ -- (BOOL)isRunning; - -/** - * Check if image has already been cached - */ -- (BOOL)diskImageExistsForURL:(NSURL *)url; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m b/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m deleted file mode 100644 index 2e893ec..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageManager.m +++ /dev/null @@ -1,254 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageManager.h" -#import - -@interface SDWebImageCombinedOperation : NSObject - -@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; -@property (copy, nonatomic) void (^cancelBlock)(); -@property (strong, nonatomic) NSOperation *cacheOperation; - -@end - -@interface SDWebImageManager () - -@property (strong, nonatomic, readwrite) SDImageCache *imageCache; -@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; -@property (strong, nonatomic) NSMutableArray *failedURLs; -@property (strong, nonatomic) NSMutableArray *runningOperations; - -@end - -@implementation SDWebImageManager - -+ (id)sharedManager { - static dispatch_once_t once; - static id instance; - dispatch_once(&once, ^{ - instance = [self new]; - }); - return instance; -} - -- (id)init { - if ((self = [super init])) { - _imageCache = [self createCache]; - _imageDownloader = [SDWebImageDownloader new]; - _failedURLs = [NSMutableArray new]; - _runningOperations = [NSMutableArray new]; - } - return self; -} - -- (SDImageCache *)createCache { - return [SDImageCache sharedImageCache]; -} - -- (NSString *)cacheKeyForURL:(NSURL *)url { - if (self.cacheKeyFilter) { - return self.cacheKeyFilter(url); - } - else { - return [url absoluteString]; - } -} - -- (BOOL)diskImageExistsForURL:(NSURL *)url { - NSString *key = [self cacheKeyForURL:url]; - return [self.imageCache diskImageExistsWithKey:key]; -} - -- (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { - // Invoking this method without a completedBlock is pointless - NSParameterAssert(completedBlock); - - // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't - // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. - if ([url isKindOfClass:NSString.class]) { - url = [NSURL URLWithString:(NSString *)url]; - } - - // Prevents app crashing on argument type error like sending NSNull instead of NSURL - if (![url isKindOfClass:NSURL.class]) { - url = nil; - } - - __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; - __weak SDWebImageCombinedOperation *weakOperation = operation; - - BOOL isFailedUrl = NO; - @synchronized (self.failedURLs) { - isFailedUrl = [self.failedURLs containsObject:url]; - } - - if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { - dispatch_main_sync_safe(^{ - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; - completedBlock(nil, error, SDImageCacheTypeNone, YES); - }); - return operation; - } - - @synchronized (self.runningOperations) { - [self.runningOperations addObject:operation]; - } - NSString *key = [self cacheKeyForURL:url]; - - operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { - if (operation.isCancelled) { - @synchronized (self.runningOperations) { - [self.runningOperations removeObject:operation]; - } - - return; - } - - if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { - if (image && options & SDWebImageRefreshCached) { - dispatch_main_sync_safe(^{ - // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image - // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. - completedBlock(image, nil, cacheType, YES); - }); - } - - // download if no image or requested to refresh anyway, and download allowed by delegate - SDWebImageDownloaderOptions downloaderOptions = 0; - if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; - if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; - if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; - if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; - if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; - if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; - if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; - if (image && options & SDWebImageRefreshCached) { - // force progressive off if image already cached but forced refreshing - downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; - // ignore image read from NSURLCache if image if cached but force refreshing - downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; - } - id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { - if (weakOperation.isCancelled) { - dispatch_main_sync_safe(^{ - completedBlock(nil, nil, SDImageCacheTypeNone, finished); - }); - } - else if (error) { - dispatch_main_sync_safe(^{ - completedBlock(nil, error, SDImageCacheTypeNone, finished); - }); - - if (error.code != NSURLErrorNotConnectedToInternet) { - @synchronized (self.failedURLs) { - [self.failedURLs addObject:url]; - } - } - } - else { - BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); - - if (options & SDWebImageRefreshCached && image && !downloadedImage) { - // Image refresh hit the NSURLCache cache, do not call the completion block - } - // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it - else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ - UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; - - dispatch_main_sync_safe(^{ - completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished); - }); - - if (transformedImage && finished) { - BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; - [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk]; - } - }); - } - else { - dispatch_main_sync_safe(^{ - completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished); - }); - - if (downloadedImage && finished) { - [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; - } - } - } - - if (finished) { - @synchronized (self.runningOperations) { - [self.runningOperations removeObject:operation]; - } - } - }]; - operation.cancelBlock = ^{ - [subOperation cancel]; - }; - } - else if (image) { - dispatch_main_sync_safe(^{ - completedBlock(image, nil, cacheType, YES); - }); - @synchronized (self.runningOperations) { - [self.runningOperations removeObject:operation]; - } - } - else { - // Image not in cache and download disallowed by delegate - dispatch_main_sync_safe(^{ - completedBlock(nil, nil, SDImageCacheTypeNone, YES); - }); - @synchronized (self.runningOperations) { - [self.runningOperations removeObject:operation]; - } - } - }]; - - return operation; -} - -- (void)cancelAll { - @synchronized (self.runningOperations) { - [self.runningOperations makeObjectsPerformSelector:@selector(cancel)]; - [self.runningOperations removeAllObjects]; - } -} - -- (BOOL)isRunning { - return self.runningOperations.count > 0; -} - -@end - -@implementation SDWebImageCombinedOperation - -- (void)setCancelBlock:(void (^)())cancelBlock { - if (self.isCancelled) { - if (cancelBlock) cancelBlock(); - } - else { - _cancelBlock = [cancelBlock copy]; - } -} - -- (void)cancel { - self.cancelled = YES; - if (self.cacheOperation) { - [self.cacheOperation cancel]; - self.cacheOperation = nil; - } - if (self.cancelBlock) { - self.cancelBlock(); - self.cancelBlock = nil; - } -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h b/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h deleted file mode 100644 index 71094ee..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImageOperation.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import - -@protocol SDWebImageOperation - -- (void)cancel; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h deleted file mode 100644 index 991602a..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import -#import "SDWebImageManager.h" - -@class SDWebImagePrefetcher; - -@protocol SDWebImagePrefetcherDelegate - -@optional - -/** - * Called when an image was prefetched. - * - * @param imagePrefetcher The current image prefetcher - * @param imageURL The image url that was prefetched - * @param finishedCount The total number of images that were prefetched - * @param totalCount The total number of images that need to be prefetched - */ -- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; - -/** - * Called when all images are prefetched. - * @param imagePrefetcher The current image prefetcher - * @param totalCount The total number of images that need to be prefetched - * @param skippedCount The total number of images that were skipped - */ -- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; - -@end - - -/** - * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. - */ -@interface SDWebImagePrefetcher : NSObject - -/** - * Maximum number of URLs to prefetch at the same time. Defaults to 3. - */ -@property (nonatomic, assign) NSUInteger maxConcurrentDownloads; - -/** - * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. - */ -@property (nonatomic, assign) SDWebImageOptions options; - -@property (weak, nonatomic) id delegate; - -/** - * Return the global image prefetcher instance. - */ -+ (SDWebImagePrefetcher *)sharedImagePrefetcher; - -/** - * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, - * currently one image is downloaded at a time, - * and skips images for failed downloads and proceed to the next image in the list - * - * @param urls list of URLs to prefetch - */ -- (void)prefetchURLs:(NSArray *)urls; - -/** - * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, - * currently one image is downloaded at a time, - * and skips images for failed downloads and proceed to the next image in the list - * - * @param urls list of URLs to prefetch - * @param progressBlock block to be called when progress updates - * @param completionBlock block to be called when prefetching is completed - */ -- (void)prefetchURLs:(NSArray *)urls progress:(void (^)(NSUInteger, NSUInteger))progressBlock completed:(void (^)(NSUInteger, NSUInteger))completionBlock; - -/** - * Remove and cancel queued list - */ -- (void)cancelPrefetching; - - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m b/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m deleted file mode 100644 index 595a9a9..0000000 --- a/Sample App/JTSImageVC/SDWebImage/SDWebImagePrefetcher.m +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImagePrefetcher.h" - -@interface SDWebImagePrefetcher () - -@property (strong, nonatomic) SDWebImageManager *manager; -@property (strong, nonatomic) NSArray *prefetchURLs; -@property (assign, nonatomic) NSUInteger requestedCount; -@property (assign, nonatomic) NSUInteger skippedCount; -@property (assign, nonatomic) NSUInteger finishedCount; -@property (assign, nonatomic) NSTimeInterval startedTime; -@property (copy, nonatomic) void (^completionBlock)(NSUInteger, NSUInteger); -@property (copy, nonatomic) void (^progressBlock)(NSUInteger, NSUInteger); - -@end - -@implementation SDWebImagePrefetcher - -+ (SDWebImagePrefetcher *)sharedImagePrefetcher { - static dispatch_once_t once; - static id instance; - dispatch_once(&once, ^{ - instance = [self new]; - }); - return instance; -} - -- (id)init { - if ((self = [super init])) { - _manager = [SDWebImageManager new]; - _options = SDWebImageLowPriority; - self.maxConcurrentDownloads = 3; - } - return self; -} - -- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { - self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; -} - -- (NSUInteger)maxConcurrentDownloads { - return self.manager.imageDownloader.maxConcurrentDownloads; -} - -- (void)startPrefetchingAtIndex:(NSUInteger)index { - if (index >= self.prefetchURLs.count) return; - self.requestedCount++; - [self.manager downloadWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (!finished) return; - self.finishedCount++; - - if (image) { - if (self.progressBlock) { - self.progressBlock(self.finishedCount,[self.prefetchURLs count]); - } -#ifdef SD_VERBOSE - NSLog(@"Prefetched %d out of %d", self.finishedCount, self.prefetchURLs.count); -#endif - } - else { - if (self.progressBlock) { - self.progressBlock(self.finishedCount,[self.prefetchURLs count]); - } -#ifdef SD_VERBOSE - NSLog(@"Prefetched %d out of %d (Failed)", self.finishedCount, [self.prefetchURLs count]); -#endif - - // Add last failed - self.skippedCount++; - } - if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { - [self.delegate imagePrefetcher:self - didPrefetchURL:self.prefetchURLs[index] - finishedCount:self.finishedCount - totalCount:self.prefetchURLs.count - ]; - } - - if (self.prefetchURLs.count > self.requestedCount) { - [self startPrefetchingAtIndex:self.requestedCount]; - } - else if (self.finishedCount + self.skippedCount == self.requestedCount) { - [self reportStatus]; - if (self.completionBlock) { - self.completionBlock(self.finishedCount, self.skippedCount); - self.completionBlock = nil; - } - } - }]; -} - -- (void)reportStatus { - NSUInteger total = [self.prefetchURLs count]; -#ifdef SD_VERBOSE - NSLog(@"Finished prefetching (%d successful, %d skipped, timeElasped %.2f)", total - self.skippedCount, self.skippedCount, CFAbsoluteTimeGetCurrent() - self.startedTime); -#endif - if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { - [self.delegate imagePrefetcher:self - didFinishWithTotalCount:(total - self.skippedCount) - skippedCount:self.skippedCount - ]; - } -} - -- (void)prefetchURLs:(NSArray *)urls { - [self prefetchURLs:urls progress:nil completed:nil]; -} - -- (void)prefetchURLs:(NSArray *)urls progress:(void (^)(NSUInteger, NSUInteger))progressBlock completed:(void (^)(NSUInteger, NSUInteger))completionBlock { - [self cancelPrefetching]; // Prevent duplicate prefetch request - self.startedTime = CFAbsoluteTimeGetCurrent(); - self.prefetchURLs = urls; - self.completionBlock = completionBlock; - self.progressBlock = progressBlock; - - // Starts prefetching from the very first image on the list with the max allowed concurrency - NSUInteger listCount = self.prefetchURLs.count; - for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { - [self startPrefetchingAtIndex:i]; - } -} - -- (void)cancelPrefetching { - self.prefetchURLs = nil; - self.skippedCount = 0; - self.requestedCount = 0; - self.finishedCount = 0; - [self.manager cancelAll]; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h deleted file mode 100644 index 1f5d2c8..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.h +++ /dev/null @@ -1,179 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageCompat.h" -#import "SDWebImageManager.h" - -/** - * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. - */ -@interface UIButton (WebCache) - -/** - * Set the imageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state; - -/** - * Set the imageView `image` with an `url` and a placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @see setImageWithURL:placeholderImage:options: - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; - -/** - * Set the imageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; - -/** - * Set the imageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the imageView `image` with an `url`, placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the imageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the backgroundImageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; - -/** - * Set the backgroundImageView `image` with an `url` and a placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @see setImageWithURL:placeholderImage:options: - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; - -/** - * Set the backgroundImageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; - -/** - * Set the backgroundImageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param completedBlock A block object to be executed after the request operation - * completed. This block has no return value and takes three argument: the requested - * `UIImage` object, the `NSError` object describing error that occurred, and an - * `SDImageCacheType` enum describing the source of the image obtained from. - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the backgroundImageView `image` with an `url`, placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param state The state that uses the specified title. The values are described in UIControlState. - * @param placeholder The image to be set initially, until the image request finishes. - * @param completedBlock A block object to be executed after the request operation - * completed. This block has no return value and takes three argument: the requested - * `UIImage` object, the `NSError` object describing error that occurred, and an - * `SDImageCacheType` enum describing the source of the image obtained from. - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the backgroundImageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - * @param completedBlock A block object to be executed after the request operation - * completed. This block has no return value and takes three argument: the requested - * `UIImage` object, the `NSError` object describing error that occurred, and an - * `SDImageCacheType` enum describing the source of the image obtained from. - */ -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Cancel the current download - */ -- (void)cancelCurrentImageLoad; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m b/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m deleted file mode 100644 index 7f849e7..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIButton+WebCache.m +++ /dev/null @@ -1,114 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "UIButton+WebCache.h" -#import "objc/runtime.h" - -static char operationKey; - -@implementation UIButton (WebCache) - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { - [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { - [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { - [self setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { - [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; -} - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { - [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; -} - -- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { - [self cancelCurrentImageLoad]; - - [self setImage:placeholder forState:state]; - - if (url) { - __weak UIButton *wself = self; - id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (!wself) return; - dispatch_main_sync_safe(^{ - __strong UIButton *sself = wself; - if (!sself) return; - if (image) { - [sself setImage:image forState:state]; - } - if (completedBlock && finished) { - completedBlock(image, error, cacheType); - } - }); - }]; - objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { - [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { - [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { - [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { - [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { - [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; -} - -- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { - [self cancelCurrentImageLoad]; - - [self setBackgroundImage:placeholder forState:state]; - - if (url) { - __weak UIButton *wself = self; - id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (!wself) return; - dispatch_main_sync_safe(^{ - __strong UIButton *sself = wself; - if (!sself) return; - if (image) { - [sself setBackgroundImage:image forState:state]; - } - if (completedBlock && finished) { - completedBlock(image, error, cacheType); - } - }); - }]; - objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } -} - - -- (void)cancelCurrentImageLoad { - // Cancel in progress downloader from queue - id operation = objc_getAssociatedObject(self, &operationKey); - if (operation) { - [operation cancel]; - objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h deleted file mode 100755 index 084f424..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// UIImage+GIF.h -// LBGIFImage -// -// Created by Laurin Brandner on 06.01.12. -// Copyright (c) 2012 __MyCompanyName__. All rights reserved. -// - -#import - -@interface UIImage (GIF) - -+ (UIImage *)sd_animatedGIFNamed:(NSString *)name; - -+ (UIImage *)sd_animatedGIFWithData:(NSData *)data; - -- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m b/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m deleted file mode 100755 index f48d179..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImage+GIF.m +++ /dev/null @@ -1,158 +0,0 @@ -// -// UIImage+GIF.m -// LBGIFImage -// -// Created by Laurin Brandner on 06.01.12. -// Copyright (c) 2012 __MyCompanyName__. All rights reserved. -// - -#import "UIImage+GIF.h" -#import - -@implementation UIImage (GIF) - -+ (UIImage *)sd_animatedGIFWithData:(NSData *)data { - if (!data) { - return nil; - } - - CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); - - size_t count = CGImageSourceGetCount(source); - - UIImage *animatedImage; - - if (count <= 1) { - animatedImage = [[UIImage alloc] initWithData:data]; - } - else { - NSMutableArray *images = [NSMutableArray array]; - - NSTimeInterval duration = 0.0f; - - for (size_t i = 0; i < count; i++) { - CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); - - duration += [self frameDurationAtIndex:i source:source]; - - [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; - - CGImageRelease(image); - } - - if (!duration) { - duration = (1.0f / 10.0f) * count; - } - - animatedImage = [UIImage animatedImageWithImages:images duration:duration]; - } - - CFRelease(source); - - return animatedImage; -} - -+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { - float frameDuration = 0.1f; - CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); - NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; - NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; - - NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; - if (delayTimeUnclampedProp) { - frameDuration = [delayTimeUnclampedProp floatValue]; - } - else { - - NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; - if (delayTimeProp) { - frameDuration = [delayTimeProp floatValue]; - } - } - - // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. - // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify - // a duration of <= 10 ms. See and - // for more information. - - if (frameDuration < 0.011f) { - frameDuration = 0.100f; - } - - CFRelease(cfFrameProperties); - return frameDuration; -} - -+ (UIImage *)sd_animatedGIFNamed:(NSString *)name { - CGFloat scale = [UIScreen mainScreen].scale; - - if (scale > 1.0f) { - NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; - - NSData *data = [NSData dataWithContentsOfFile:retinaPath]; - - if (data) { - return [UIImage sd_animatedGIFWithData:data]; - } - - NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; - - data = [NSData dataWithContentsOfFile:path]; - - if (data) { - return [UIImage sd_animatedGIFWithData:data]; - } - - return [UIImage imageNamed:name]; - } - else { - NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; - - NSData *data = [NSData dataWithContentsOfFile:path]; - - if (data) { - return [UIImage sd_animatedGIFWithData:data]; - } - - return [UIImage imageNamed:name]; - } -} - -- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { - if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { - return self; - } - - CGSize scaledSize = size; - CGPoint thumbnailPoint = CGPointZero; - - CGFloat widthFactor = size.width / self.size.width; - CGFloat heightFactor = size.height / self.size.height; - CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; - scaledSize.width = self.size.width * scaleFactor; - scaledSize.height = self.size.height * scaleFactor; - - if (widthFactor > heightFactor) { - thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; - } - else if (widthFactor < heightFactor) { - thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; - } - - NSMutableArray *scaledImages = [NSMutableArray array]; - - UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); - - for (UIImage *image in self.images) { - [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; - UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); - - [scaledImages addObject:newImage]; - } - - UIGraphicsEndImageContext(); - - return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h deleted file mode 100644 index 186ebc0..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// UIImage+MultiFormat.h -// SDWebImage -// -// Created by Olivier Poitrey on 07/06/13. -// Copyright (c) 2013 Dailymotion. All rights reserved. -// - -#import - -@interface UIImage (MultiFormat) - -+ (UIImage *)sd_imageWithData:(NSData *)data; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m b/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m deleted file mode 100644 index e2e3e80..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImage+MultiFormat.m +++ /dev/null @@ -1,39 +0,0 @@ -// -// UIImage+MultiFormat.m -// SDWebImage -// -// Created by Olivier Poitrey on 07/06/13. -// Copyright (c) 2013 Dailymotion. All rights reserved. -// - -#import "UIImage+MultiFormat.h" -#import "UIImage+GIF.h" -#import "NSData+ImageContentType.h" - -#ifdef SD_WEBP -#import "UIImage+WebP.h" -#endif - -@implementation UIImage (MultiFormat) - -+ (UIImage *)sd_imageWithData:(NSData *)data { - UIImage *image; - NSString *imageContentType = [NSData contentTypeForImageData:data]; - if ([imageContentType isEqualToString:@"image/gif"]) { - image = [UIImage sd_animatedGIFWithData:data]; - } -#ifdef SD_WEBP - else if ([imageContentType isEqualToString:@"image/webp"]) - { - image = [UIImage sd_imageWithWebPData:data]; - } -#endif - else { - image = [[UIImage alloc] initWithData:data]; - } - - - return image; -} - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h deleted file mode 100644 index 46f1f0b..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "SDWebImageCompat.h" -#import "SDWebImageManager.h" - -/** - * Integrates SDWebImage async downloading and caching of remote images with UIImageView. - * - * Usage with a UITableViewCell sub-class: - * - * @code - -#import - -... - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath -{ - static NSString *MyIdentifier = @"MyIdentifier"; - - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; - - if (cell == nil) { - cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] - autorelease]; - } - - // Here we use the provided setImageWithURL: method to load the web image - // Ensure you use a placeholder image otherwise cells will be initialized with no image - [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] - placeholderImage:[UIImage imageNamed:@"placeholder"]]; - - cell.textLabel.text = @"My Text"; - return cell; -} - - * @endcode - */ -@interface UIImageView (WebCache) - -/** - * Set the imageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - */ -- (void)setImageWithURL:(NSURL *)url; - -/** - * Set the imageView `image` with an `url` and a placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @see setImageWithURL:placeholderImage:options: - */ -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; - -/** - * Set the imageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - */ -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; - -/** - * Set the imageView `image` with an `url`. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the imageView `image` with an `url`, placeholder. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the imageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Set the imageView `image` with an `url`, placeholder and custom options. - * - * The downloand is asynchronous and cached. - * - * @param url The url for the image. - * @param placeholder The image to be set initially, until the image request finishes. - * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. - * @param progressBlock A block called while image is downloading - * @param completedBlock A block called when operation has been completed. This block as no return value - * and takes the requested UIImage as first parameter. In case of error the image parameter - * is nil and the second parameter may contain an NSError. The third parameter is a Boolean - * indicating if the image was retrived from the local cache of from the network. - */ -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; - -/** - * Download an array of images and starts them in an animation loop - * - *@param arrayOfURLs An array of NSURL - */ -- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; - -/** - * Cancel the current download - */ -- (void)cancelCurrentImageLoad; - -- (void)cancelCurrentArrayLoad; - -@end diff --git a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m b/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m deleted file mode 100644 index ed65a0e..0000000 --- a/Sample App/JTSImageVC/SDWebImage/UIImageView+WebCache.m +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This file is part of the SDWebImage package. - * (c) Olivier Poitrey - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -#import "UIImageView+WebCache.h" -#import "objc/runtime.h" - -static char operationKey; -static char operationArrayKey; - -@implementation UIImageView (WebCache) - -- (void)setImageWithURL:(NSURL *)url { - [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { - [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { - [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; -} - -- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { - [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; -} - -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { - [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; -} - -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { - [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; -} - -- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { - [self cancelCurrentImageLoad]; - - self.image = placeholder; - - if (url) { - __weak UIImageView *wself = self; - id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (!wself) return; - dispatch_main_sync_safe(^{ - if (!wself) return; - if (image) { - wself.image = image; - [wself setNeedsLayout]; - } - if (completedBlock && finished) { - completedBlock(image, error, cacheType); - } - }); - }]; - objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } -} - -- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { - [self cancelCurrentArrayLoad]; - __weak UIImageView *wself = self; - - NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; - - for (NSURL *logoImageURL in arrayOfURLs) { - id operation = [SDWebImageManager.sharedManager downloadWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { - if (!wself) return; - dispatch_main_sync_safe(^{ - __strong UIImageView *sself = wself; - [sself stopAnimating]; - if (sself && image) { - NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; - if (!currentImages) { - currentImages = [[NSMutableArray alloc] init]; - } - [currentImages addObject:image]; - - sself.animationImages = currentImages; - [sself setNeedsLayout]; - } - [sself startAnimating]; - }); - }]; - [operationsArray addObject:operation]; - } - - objc_setAssociatedObject(self, &operationArrayKey, [NSArray arrayWithArray:operationsArray], OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (void)cancelCurrentImageLoad { - // Cancel in progress downloader from queue - id operation = objc_getAssociatedObject(self, &operationKey); - if (operation) { - [operation cancel]; - objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } -} - -- (void)cancelCurrentArrayLoad { - // Cancel in progress downloader from queue - NSArray *operations = objc_getAssociatedObject(self, &operationArrayKey); - for (id operation in operations) { - if (operation) { - [operation cancel]; - } - } - objc_setAssociatedObject(self, &operationArrayKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -@end diff --git a/Source/JTSImageViewController.h b/Source/JTSImageViewController.h index a8fa642..b2e9eec 100644 --- a/Source/JTSImageViewController.h +++ b/Source/JTSImageViewController.h @@ -90,7 +90,7 @@ extern CGFloat const JTSImageViewController_DefaultBackgroundBlurRadius; backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle; /** - Initializer for using JTSImageViewController with a custom image downloader for the purpose of easily allowing cooperation with image caching 3rd party libraries like SDWebImage. + Initializer for using JTSImageViewController with a custom image downloader for the purpose of easily allowing cooperation with 3rd party libraries for downloading or caching images such as SDWebImage. Caller is responsible for setting the image view via customImageLoadingDidFinish: when image download is finished. @param imageInfo The source info for image and transition metadata. Required. @@ -103,14 +103,14 @@ extern CGFloat const JTSImageViewController_DefaultBackgroundBlurRadius; - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo mode:(JTSImageViewControllerMode)mode backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle - customImageProgress:(NSProgress*)customImageProgress; + customImageLoadingProgress:(NSProgress*)customImageProgress; /** Image setter intended for use only when using custom image downloader to provide the UIImage to be used upon download/retrieval completion. - @param customImage Full image to be displayed + @param image Image to be displayed */ --(void)customImageSetter:(UIImage*)customImage; +-(void)customImageLoadingDidFinish:(UIImage*)image; /** JTSImageViewController is presented from viewController as a UIKit modal view controller. diff --git a/Source/JTSImageViewController.m b/Source/JTSImageViewController.m index 210fe02..e319bcb 100644 --- a/Source/JTSImageViewController.m +++ b/Source/JTSImageViewController.m @@ -100,18 +100,11 @@ @implementation JTSImageViewController - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo mode:(JTSImageViewControllerMode)mode backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle { - - self = [super initWithNibName:nil bundle:nil]; - if (self) { - _backgroundBlurRadius = JTSImageViewController_DefaultBackgroundBlurRadius; - _alphaForBackgroundDimmingOverlay = JTSImageViewController_DefaultAlphaForBackgroundDimmingOverlay; + + if (self = [self init]) { _imageInfo = imageInfo; - _currentSnapshotRotationTransform = CGAffineTransformIdentity; _mode = mode; _backgroundStyle = backgroundStyle; - _accessibilityLabel = [self defaultAccessibilityLabelForScrollView]; - _accessibilityHintZoomedIn = [self defaultAccessibilityHintForScrollView:YES]; - _accessibilityHintZoomedOut = [self defaultAccessibilityHintForScrollView:NO]; if (_mode == JTSImageViewControllerMode_Image) { [self setupImageAndDownloadIfNecessary:imageInfo]; } @@ -122,25 +115,17 @@ - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo mode:(JTSImageViewControllerMode)mode backgroundStyle:(JTSImageViewControllerBackgroundStyle)backgroundStyle - customImageProgress:(NSProgress*)customImageProgress{ + customImageLoadingProgress:(NSProgress*)customImageProgress{ - self = [super initWithNibName:nil bundle:nil]; - if (self) { - _backgroundBlurRadius = JTSImageViewController_DefaultBackgroundBlurRadius; - _alphaForBackgroundDimmingOverlay = JTSImageViewController_DefaultAlphaForBackgroundDimmingOverlay; + if (self = [self init]) { _imageInfo = imageInfo; - _currentSnapshotRotationTransform = CGAffineTransformIdentity; _mode = mode; _backgroundStyle = backgroundStyle; - _accessibilityLabel = [self defaultAccessibilityLabelForScrollView]; - _accessibilityHintZoomedIn = [self defaultAccessibilityHintForScrollView:YES]; - _accessibilityHintZoomedOut = [self defaultAccessibilityHintForScrollView:NO]; if (_mode == JTSImageViewControllerMode_Image) { _imageDownloadUsingCustom = YES; //set placeholder [self setImage:imageInfo.placeholderImage]; - //caller is responsible for setting the image view via block - //progress timer will call progress completion block + //retain NSProgress to be used in place of imageDownloadDataTask _customImageProgress = customImageProgress; [self startProgressTimer]; } @@ -148,10 +133,10 @@ - (instancetype)initWithImageInfo:(JTSImageInfo *)imageInfo return self; } --(void)customImageSetter:(UIImage*)customImage{ +-(void)customImageLoadingDidFinish:(UIImage*)image{ - if(customImage && self.imageDownloadUsingCustom){ - [self downloadCompletion:customImage]; + if(image && self.imageDownloadUsingCustom){ + [self downloadCompletion:image]; } } @@ -298,6 +283,20 @@ - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInte #pragma mark - Setup +- (instancetype)init{ + + self = [super initWithNibName:nil bundle:nil]; + if (self) { + _backgroundBlurRadius = JTSImageViewController_DefaultBackgroundBlurRadius; + _alphaForBackgroundDimmingOverlay = JTSImageViewController_DefaultAlphaForBackgroundDimmingOverlay; + _currentSnapshotRotationTransform = CGAffineTransformIdentity; + _accessibilityLabel = [self defaultAccessibilityLabelForScrollView]; + _accessibilityHintZoomedIn = [self defaultAccessibilityHintForScrollView:YES]; + _accessibilityHintZoomedOut = [self defaultAccessibilityHintForScrollView:NO]; + } + return self; +} + - (void)setupImageAndDownloadIfNecessary:(JTSImageInfo *)imageInfo { if (imageInfo.image) { [self setImage:imageInfo.image];