This commit is contained in:
2025-10-27 21:55:05 +08:00
parent d4ebfb9909
commit a6c077a42d
414 changed files with 55606 additions and 21 deletions

View File

@@ -0,0 +1,340 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_MAC
#import "SDWebImageManager.h"
/**
* Integrates SDWebImage async downloading and caching of remote images with NSButton.
*/
@interface NSButton (WebCache)
#pragma mark - Image
/**
* Get the current image URL.
*/
@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL;
/**
* Set the button `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url` and a placeholder.
*
* The download 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 sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
/**
* Set the button `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
#pragma mark - Alternate Image
/**
* Get the current alternateImage URL.
*/
@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentAlternateImageURL;
/**
* Set the button `alternateImage` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT;
/**
* Set the button `alternateImage` with an `url` and a placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @see sd_setAlternateImageWithURL:placeholderImage:options:
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT;
/**
* Set the button `alternateImage` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the button `alternateImage` with an `url`, placeholder, custom options and context.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
/**
* Set the button `alternateImage` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the alternateImage parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the alternateImage was retrieved from the local cache or from the network.
* The fourth parameter is the original alternateImage url.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `alternateImage` with an `url`, placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the alternateImage parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the alternateImage was retrieved from the local cache or from the network.
* The fourth parameter is the original alternateImage url.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the button `alternateImage` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the alternateImage parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the alternateImage was retrieved from the local cache or from the network.
* The fourth parameter is the original alternateImage url.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `alternateImage` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values.
* @param progressBlock A block called while alternateImage is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the alternateImage parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the alternateImage was retrieved from the local cache or from the network.
* The fourth parameter is the original alternateImage url.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `alternateImage` with an `url`, placeholder, custom options and context.
*
* The download is asynchronous and cached.
*
* @param url The url for the alternateImage.
* @param placeholder The alternateImage to be set initially, until the alternateImage request finishes.
* @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while alternateImage is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the alternateImage parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the alternateImage was retrieved from the local cache or from the network.
* The fourth parameter is the original alternateImage url.
*/
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
#pragma mark - Cancel
/**
* Cancel the current image download
*/
- (void)sd_cancelCurrentImageLoad;
/**
* Cancel the current alternateImage download
*/
- (void)sd_cancelCurrentAlternateImageLoad;
@end
#endif

View File

@@ -0,0 +1,162 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "NSButton+WebCache.h"
#if SD_MAC
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"
#import "UIView+WebCacheState.h"
#import "UIView+WebCache.h"
#import "SDInternalMacros.h"
@implementation NSButton (WebCache)
#pragma mark - Image
- (void)sd_setImageWithURL:(nullable NSURL *)url {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
context:context
setImageBlock:nil
progress:progressBlock
completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageURL);
}
}];
}
#pragma mark - Alternate Image
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url {
[self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}
- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
mutableContext[SDWebImageContextSetImageOperationKey] = @keypath(self, alternateImage);
@weakify(self);
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
context:mutableContext
setImageBlock:^(NSImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
@strongify(self);
self.alternateImage = image;
}
progress:progressBlock
completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageURL);
}
}];
}
#pragma mark - Cancel
- (void)sd_cancelCurrentImageLoad {
[self sd_cancelImageLoadOperationWithKey:nil];
}
- (void)sd_cancelCurrentAlternateImageLoad {
[self sd_cancelImageLoadOperationWithKey:@keypath(self, alternateImage)];
}
#pragma mark - State
- (NSURL *)sd_currentImageURL {
return [self sd_imageLoadStateForKey:nil].url;
}
#pragma mark - Alternate State
- (NSURL *)sd_currentAlternateImageURL {
return [self sd_imageLoadStateForKey:@keypath(self, alternateImage)].url;
}
@end
#endif

View File

@@ -0,0 +1,63 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Fabrice Aneche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
/**
You can use switch case like normal enum. It's also recommended to add a default case. You should not assume anything about the raw value.
For custom coder plugin, it can also extern the enum for supported format. See `SDImageCoder` for more detailed information.
*/
typedef NSInteger SDImageFormat NS_TYPED_EXTENSIBLE_ENUM;
static const SDImageFormat SDImageFormatUndefined = -1;
static const SDImageFormat SDImageFormatJPEG = 0;
static const SDImageFormat SDImageFormatPNG = 1;
static const SDImageFormat SDImageFormatGIF = 2;
static const SDImageFormat SDImageFormatTIFF = 3;
static const SDImageFormat SDImageFormatWebP = 4;
static const SDImageFormat SDImageFormatHEIC = 5;
static const SDImageFormat SDImageFormatHEIF = 6;
static const SDImageFormat SDImageFormatPDF = 7;
static const SDImageFormat SDImageFormatSVG = 8;
static const SDImageFormat SDImageFormatBMP = 9;
static const SDImageFormat SDImageFormatRAW = 10;
/**
NSData category about the image content type and UTI.
*/
@interface NSData (ImageContentType)
/**
* Return image format
*
* @param data the input image data
*
* @return the image format as `SDImageFormat` (enum)
*/
+ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data;
/**
* Convert SDImageFormat to UTType
*
* @param format Format as SDImageFormat
* @return The UTType as CFStringRef
* @note For unknown format, `kSDUTTypeImage` abstract type will return
*/
+ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format CF_RETURNS_NOT_RETAINED NS_SWIFT_NAME(sd_UTType(from:));
/**
* Convert UTType to SDImageFormat
*
* @param uttype The UTType as CFStringRef
* @return The Format as SDImageFormat
* @note For unknown type, `SDImageFormatUndefined` will return
*/
+ (SDImageFormat)sd_imageFormatFromUTType:(nonnull CFStringRef)uttype;
@end

View File

@@ -0,0 +1,167 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Fabrice Aneche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "NSData+ImageContentType.h"
#if SD_MAC
#import <CoreServices/CoreServices.h>
#else
#import <MobileCoreServices/MobileCoreServices.h>
#endif
#import "SDImageIOAnimatedCoderInternal.h"
#define kSVGTagEnd @"</svg>"
@implementation NSData (ImageContentType)
+ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data {
if (!data) {
return SDImageFormatUndefined;
}
// File signatures table: http://www.garykessler.net/library/file_sigs.html
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return SDImageFormatJPEG;
case 0x89:
return SDImageFormatPNG;
case 0x47:
return SDImageFormatGIF;
case 0x49:
case 0x4D:
return SDImageFormatTIFF;
case 0x42:
return SDImageFormatBMP;
case 0x52: {
if (data.length >= 12) {
//RIFF....WEBP
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return SDImageFormatWebP;
}
}
break;
}
case 0x00: {
if (data.length >= 12) {
//....ftypheic ....ftypheix ....ftyphevc ....ftyphevx
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(4, 8)] encoding:NSASCIIStringEncoding];
if ([testString isEqualToString:@"ftypheic"]
|| [testString isEqualToString:@"ftypheix"]
|| [testString isEqualToString:@"ftyphevc"]
|| [testString isEqualToString:@"ftyphevx"]) {
return SDImageFormatHEIC;
}
//....ftypmif1 ....ftypmsf1
if ([testString isEqualToString:@"ftypmif1"] || [testString isEqualToString:@"ftypmsf1"]) {
return SDImageFormatHEIF;
}
}
break;
}
case 0x25: {
if (data.length >= 4) {
//%PDF
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(1, 3)] encoding:NSASCIIStringEncoding];
if ([testString isEqualToString:@"PDF"]) {
return SDImageFormatPDF;
}
}
break;
}
case 0x3C: {
// Check end with SVG tag
if ([data rangeOfData:[kSVGTagEnd dataUsingEncoding:NSUTF8StringEncoding] options:NSDataSearchBackwards range: NSMakeRange(data.length - MIN(100, data.length), MIN(100, data.length))].location != NSNotFound) {
return SDImageFormatSVG;
}
break;
}
}
return SDImageFormatUndefined;
}
+ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format {
CFStringRef UTType;
switch (format) {
case SDImageFormatJPEG:
UTType = kSDUTTypeJPEG;
break;
case SDImageFormatPNG:
UTType = kSDUTTypePNG;
break;
case SDImageFormatGIF:
UTType = kSDUTTypeGIF;
break;
case SDImageFormatTIFF:
UTType = kSDUTTypeTIFF;
break;
case SDImageFormatWebP:
UTType = kSDUTTypeWebP;
break;
case SDImageFormatHEIC:
UTType = kSDUTTypeHEIC;
break;
case SDImageFormatHEIF:
UTType = kSDUTTypeHEIF;
break;
case SDImageFormatPDF:
UTType = kSDUTTypePDF;
break;
case SDImageFormatSVG:
UTType = kSDUTTypeSVG;
break;
case SDImageFormatBMP:
UTType = kSDUTTypeBMP;
break;
case SDImageFormatRAW:
UTType = kSDUTTypeRAW;
break;
default:
// default is kUTTypeImage abstract type
UTType = kSDUTTypeImage;
break;
}
return UTType;
}
+ (SDImageFormat)sd_imageFormatFromUTType:(CFStringRef)uttype {
if (!uttype) {
return SDImageFormatUndefined;
}
SDImageFormat imageFormat;
if (CFStringCompare(uttype, kSDUTTypeJPEG, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatJPEG;
} else if (CFStringCompare(uttype, kSDUTTypePNG, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatPNG;
} else if (CFStringCompare(uttype, kSDUTTypeGIF, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatGIF;
} else if (CFStringCompare(uttype, kSDUTTypeTIFF, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatTIFF;
} else if (CFStringCompare(uttype, kSDUTTypeWebP, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatWebP;
} else if (CFStringCompare(uttype, kSDUTTypeHEIC, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatHEIC;
} else if (CFStringCompare(uttype, kSDUTTypeHEIF, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatHEIF;
} else if (CFStringCompare(uttype, kSDUTTypePDF, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatPDF;
} else if (CFStringCompare(uttype, kSDUTTypeSVG, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatSVG;
} else if (CFStringCompare(uttype, kSDUTTypeBMP, 0) == kCFCompareEqualTo) {
imageFormat = SDImageFormatBMP;
} else if (UTTypeConformsTo(uttype, kSDUTTypeRAW)) {
imageFormat = SDImageFormatRAW;
} else {
imageFormat = SDImageFormatUndefined;
}
return imageFormat;
}
@end

View File

@@ -0,0 +1,67 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_MAC
/**
This category is provided to easily write cross-platform(AppKit/UIKit) code. For common usage, see `UIImage+Metadata.h`.
*/
@interface NSImage (Compatibility)
/**
The underlying Core Graphics image object. This will actually use `CGImageForProposedRect` with the image size.
*/
@property (nonatomic, readonly, nullable) CGImageRef CGImage;
/**
The underlying Core Image data. This will actually use `bestRepresentationForRect` with the image size to find the `NSCIImageRep`.
*/
@property (nonatomic, readonly, nullable) CIImage *CIImage;
/**
The scale factor of the image. This wil actually use `bestRepresentationForRect` with image size and pixel size to calculate the scale factor. If failed, use the default value 1.0. Should be greater than or equal to 1.0.
*/
@property (nonatomic, readonly) CGFloat scale;
// These are convenience methods to make AppKit's `NSImage` match UIKit's `UIImage` behavior. The scale factor should be greater than or equal to 1.0.
/**
Returns an image object with the scale factor and orientation. The representation is created from the Core Graphics image object.
@note The difference between this and `initWithCGImage:size` is that `initWithCGImage:size` will actually create a `NSCGImageSnapshotRep` representation and always use `backingScaleFactor` as scale factor. So we should avoid it and use `NSBitmapImageRep` with `initWithCGImage:` instead.
@note The difference between this and UIKit's `UIImage` equivalent method is the way to process orientation. If the provided image orientation is not equal to Up orientation, this method will firstly rotate the CGImage to the correct orientation to work compatible with `NSImageView`. However, UIKit will not actually rotate CGImage and just store it as `imageOrientation` property.
@param cgImage A Core Graphics image object
@param scale The image scale factor
@param orientation The orientation of the image data
@return The image object
*/
- (nonnull instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation;
/**
Initializes and returns an image object with the specified Core Image object. The representation is `NSCIImageRep`.
@param ciImage A Core Image image object
@param scale The image scale factor
@param orientation The orientation of the image data
@return The image object
*/
- (nonnull instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation;
/**
Returns an image object with the scale factor. The representation is created from the image data.
@note The difference between these this and `initWithData:` is that `initWithData:` will always use `backingScaleFactor` as scale factor.
@param data The image data
@param scale The image scale factor
@return The image object
*/
- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale;
@end
#endif

View File

@@ -0,0 +1,120 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "NSImage+Compatibility.h"
#if SD_MAC
#import "SDImageCoderHelper.h"
@implementation NSImage (Compatibility)
- (nullable CGImageRef)CGImage {
NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height);
CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:nil hints:nil];
return cgImage;
}
- (nullable CIImage *)CIImage {
NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height);
NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil];
if (![imageRep isKindOfClass:NSCIImageRep.class]) {
return nil;
}
return ((NSCIImageRep *)imageRep).CIImage;
}
- (CGFloat)scale {
CGFloat scale = 1;
NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height);
NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil];
CGFloat width = imageRep.size.width;
CGFloat height = imageRep.size.height;
CGFloat pixelWidth = (CGFloat)imageRep.pixelsWide;
CGFloat pixelHeight = (CGFloat)imageRep.pixelsHigh;
if (width > 0 && height > 0) {
CGFloat widthScale = pixelWidth / width;
CGFloat heightScale = pixelHeight / height;
if (widthScale == heightScale && widthScale >= 1) {
// Protect because there may be `NSImageRepMatchesDevice` (0)
scale = widthScale;
}
}
return scale;
}
- (instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation {
NSBitmapImageRep *imageRep;
if (orientation != kCGImagePropertyOrientationUp) {
// AppKit design is different from UIKit. Where CGImage based image rep does not respect to any orientation. Only data based image rep which contains the EXIF metadata can automatically detect orientation.
// This should be nonnull, until the memory is exhausted cause `CGBitmapContextCreate` failed.
CGImageRef rotatedCGImage = [SDImageCoderHelper CGImageCreateDecoded:cgImage orientation:orientation];
imageRep = [[NSBitmapImageRep alloc] initWithCGImage:rotatedCGImage];
CGImageRelease(rotatedCGImage);
} else {
imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
}
if (scale < 1) {
scale = 1;
}
CGFloat pixelWidth = imageRep.pixelsWide;
CGFloat pixelHeight = imageRep.pixelsHigh;
NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale);
self = [self initWithSize:size];
if (self) {
imageRep.size = size;
[self addRepresentation:imageRep];
}
return self;
}
- (instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation {
NSCIImageRep *imageRep;
if (orientation != kCGImagePropertyOrientationUp) {
CIImage *rotatedCIImage = [ciImage imageByApplyingOrientation:orientation];
imageRep = [[NSCIImageRep alloc] initWithCIImage:rotatedCIImage];
} else {
imageRep = [[NSCIImageRep alloc] initWithCIImage:ciImage];
}
if (scale < 1) {
scale = 1;
}
CGFloat pixelWidth = imageRep.pixelsWide;
CGFloat pixelHeight = imageRep.pixelsHigh;
NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale);
self = [self initWithSize:size];
if (self) {
imageRep.size = size;
[self addRepresentation:imageRep];
}
return self;
}
- (instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale {
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:data];
if (!imageRep) {
return nil;
}
if (scale < 1) {
scale = 1;
}
CGFloat pixelWidth = imageRep.pixelsWide;
CGFloat pixelHeight = imageRep.pixelsHigh;
NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale);
self = [self initWithSize:size];
if (self) {
imageRep.size = size;
[self addRepresentation:imageRep];
}
return self;
}
@end
#endif

View File

@@ -0,0 +1,136 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "SDImageCoder.h"
/**
This is the protocol for SDAnimatedImage class only but not for SDAnimatedImageCoder. If you want to provide a custom animated image class with full advanced function, you can conform to this instead of the base protocol.
*/
@protocol SDAnimatedImage <SDAnimatedImageProvider>
@required
/**
Initializes and returns the image object with the specified data, scale factor and possible animation decoding options.
@note We use this to create animated image instance for normal animation decoding.
@param data The data object containing the image data.
@param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property.
@param options A dictionary containing any animation decoding options.
@return An initialized object
*/
- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale options:(nullable SDImageCoderOptions *)options;
/**
Initializes the image with an animated coder. You can use the coder to decode the image frame later.
@note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding.
@param animatedCoder An animated coder which conform `SDAnimatedImageCoder` protocol
@param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property.
@return An initialized object
*/
- (nullable instancetype)initWithAnimatedCoder:(nonnull id<SDAnimatedImageCoder>)animatedCoder scale:(CGFloat)scale;
@optional
// These methods are used for optional advanced feature, like image frame preloading.
/**
Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding.
This method may be called on background thread.
@note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage.
*/
- (void)preloadAllFrames;
/**
Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need.
*/
- (void)unloadAllFrames;
/**
Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory.
*/
@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded;
/**
Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method.
@note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding.
*/
@property (nonatomic, strong, readonly, nullable) id<SDAnimatedImageCoder> animatedCoder;
@end
/**
The image class which supports animating on `SDAnimatedImageView`. You can also use it on normal UIImageView/NSImageView.
*/
NS_SWIFT_NONISOLATED
@interface SDAnimatedImage : UIImage <SDAnimatedImage>
// This class override these methods from UIImage(NSImage), and it supports NSSecureCoding.
// You should use these methods to create a new animated image. Use other methods just call super instead.
// @note Before 5.19, these initializer will return nil for static image (when all candidate SDAnimatedImageCoder returns nil instance), like JPEG data. After 5.19, these initializer will retry for static image as well, so JPEG data will return non-nil instance. For vector image(PDF/SVG), always return nil.
// @note When the animated image frame count <= 1, all the `SDAnimatedImageProvider` protocol methods will return nil or 0 value, you'd better check the frame count before usage and keep fallback.
+ (nullable instancetype)imageNamed:(nonnull NSString *)name; // Cache in memory, no Asset Catalog support
#if __has_include(<UIKit/UITraitCollection.h>) && !SD_WATCH
+ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection; // Cache in memory, no Asset Catalog support
#else
+ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle; // Cache in memory, no Asset Catalog support
#endif
+ (nullable instancetype)imageWithContentsOfFile:(nonnull NSString *)path;
+ (nullable instancetype)imageWithData:(nonnull NSData *)data;
+ (nullable instancetype)imageWithData:(nonnull NSData *)data scale:(CGFloat)scale;
- (nullable instancetype)initWithContentsOfFile:(nonnull NSString *)path;
- (nullable instancetype)initWithData:(nonnull NSData *)data;
- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale;
/**
Current animated image format.
@note This format is only valid when `animatedImageData` not nil.
@note This actually just call `[NSData sd_imageFormatForImageData:self.animatedImageData]`
*/
@property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat;
/**
Current animated image data, you can use this to grab the compressed format data and create another animated image instance.
If this image instance is an animated image created by using animated image coder (which means using the API listed above or using `initWithAnimatedCoder:scale:`), this property is non-nil.
*/
@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData;
/**
The scale factor of the image.
@note For UIKit, this just call super instead.
@note For AppKit, `NSImage` can contains multiple image representations with different scales. However, this class does not do that from the design. We process the scale like UIKit. This will actually be calculated from image size and pixel size.
*/
@property (nonatomic, readonly) CGFloat scale;
// By default, animated image frames are returned by decoding just in time without keeping into memory. But you can choose to preload them into memory as well, See the description in `SDAnimatedImage` protocol.
// After preloaded, there is no huge difference on performance between this and UIImage's `animatedImageWithImages:duration:`. But UIImage's animation have some issues such like blanking and pausing during segue when using in `UIImageView`. It's recommend to use only if need.
/**
Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding.
This method may be called on background thread.
@note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage.
*/
- (void)preloadAllFrames;
/**
Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need.
*/
- (void)unloadAllFrames;
/**
Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory.
*/
@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded;
/**
Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method.
@note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding.
*/
@property (nonatomic, strong, readonly, nullable) id<SDAnimatedImageCoder> animatedCoder;
@end

View File

@@ -0,0 +1,449 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImage.h"
#import "NSImage+Compatibility.h"
#import "SDImageCoder.h"
#import "SDImageCodersManager.h"
#import "SDImageFrame.h"
#import "UIImage+MemoryCacheCost.h"
#import "UIImage+Metadata.h"
#import "UIImage+MultiFormat.h"
#import "SDImageCoderHelper.h"
#import "SDImageAssetManager.h"
#import "objc/runtime.h"
static CGFloat SDImageScaleFromPath(NSString *string) {
if (string.length == 0 || [string hasSuffix:@"/"]) return 1;
NSString *name = string.stringByDeletingPathExtension;
__block CGFloat scale = 1;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil];
[pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue;
}];
return scale;
}
@interface SDAnimatedImage ()
@property (nonatomic, strong) id<SDAnimatedImageCoder> animatedCoder;
@property (atomic, copy) NSArray<SDImageFrame *> *loadedAnimatedImageFrames; // Mark as atomic to keep thread-safe
@property (nonatomic, assign, getter=isAllFramesLoaded) BOOL allFramesLoaded;
@end
@implementation SDAnimatedImage
@dynamic scale; // call super
#pragma mark - UIImage override method
+ (instancetype)imageNamed:(NSString *)name {
#if __has_include(<UIKit/UITraitCollection.h>) && !SD_WATCH
return [self imageNamed:name inBundle:nil compatibleWithTraitCollection:nil];
#else
return [self imageNamed:name inBundle:nil];
#endif
}
#if __has_include(<UIKit/UITraitCollection.h>) && !SD_WATCH
+ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection {
#if SD_VISION
if (!traitCollection) {
traitCollection = UITraitCollection.currentTraitCollection;
}
#else
if (!traitCollection) {
traitCollection = UIScreen.mainScreen.traitCollection;
}
#endif
CGFloat scale = traitCollection.displayScale;
return [self imageNamed:name inBundle:bundle scale:scale];
}
#else
+ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle {
return [self imageNamed:name inBundle:bundle scale:0];
}
#endif
// 0 scale means automatically check
+ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle scale:(CGFloat)scale {
if (!name) {
return nil;
}
if (!bundle) {
bundle = [NSBundle mainBundle];
}
SDImageAssetManager *assetManager = [SDImageAssetManager sharedAssetManager];
SDAnimatedImage *image = (SDAnimatedImage *)[assetManager imageForName:name];
if ([image isKindOfClass:[SDAnimatedImage class]]) {
return image;
}
NSString *path = [assetManager getPathForName:name bundle:bundle preferredScale:&scale];
if (!path) {
return image;
}
NSData *data = [NSData dataWithContentsOfFile:path];
if (!data) {
return image;
}
image = [[self alloc] initWithData:data scale:scale];
if (image) {
[assetManager storeImage:image forName:name];
}
return image;
}
+ (instancetype)imageWithContentsOfFile:(NSString *)path {
return [[self alloc] initWithContentsOfFile:path];
}
+ (instancetype)imageWithData:(NSData *)data {
return [[self alloc] initWithData:data];
}
+ (instancetype)imageWithData:(NSData *)data scale:(CGFloat)scale {
return [[self alloc] initWithData:data scale:scale];
}
- (instancetype)initWithContentsOfFile:(NSString *)path {
NSData *data = [NSData dataWithContentsOfFile:path];
if (!data) {
return nil;
}
CGFloat scale = SDImageScaleFromPath(path);
// path extension may be useful for coder like raw-image
NSString *fileExtensionHint = path.pathExtension; // without dot
if (fileExtensionHint.length == 0) {
// Ignore file extension which is empty
fileExtensionHint = nil;
}
SDImageCoderMutableOptions *mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:1];
mutableCoderOptions[SDImageCoderDecodeFileExtensionHint] = fileExtensionHint;
return [self initWithData:data scale:scale options:[mutableCoderOptions copy]];
}
- (instancetype)initWithData:(NSData *)data {
return [self initWithData:data scale:1];
}
- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale {
return [self initWithData:data scale:scale options:nil];
}
- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale options:(SDImageCoderOptions *)options {
if (!data || data.length == 0) {
return nil;
}
// Vector image does not supported, guard firstly
SDImageFormat format = [NSData sd_imageFormatForImageData:data];
if (format == SDImageFormatSVG || format == SDImageFormatPDF) {
return nil;
}
id<SDAnimatedImageCoder> animatedCoder = nil;
SDImageCoderMutableOptions *mutableCoderOptions;
if (options != nil) {
mutableCoderOptions = [NSMutableDictionary dictionaryWithDictionary:options];
} else {
mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:1];
}
mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale);
options = [mutableCoderOptions copy];
for (id<SDImageCoder>coder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) {
if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) {
if ([coder canDecodeFromData:data]) {
animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:data options:options];
break;
}
}
}
if (animatedCoder) {
// Animated Image
return [self initWithAnimatedCoder:animatedCoder scale:scale];
} else {
// Static Image (Before 5.19 this code path return nil)
UIImage *image = [[SDImageCodersManager sharedManager] decodedImageWithData:data options:options];
if (!image) {
return nil;
}
// Vector image does not supported, guard secondly
if (image.sd_isVector) {
return nil;
}
#if SD_MAC
self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:kCGImagePropertyOrientationUp];
#else
self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation];
#endif
// Defines the associated object that holds the format for static images
super.sd_imageFormat = format;
return self;
}
}
- (instancetype)initWithAnimatedCoder:(id<SDAnimatedImageCoder>)animatedCoder scale:(CGFloat)scale {
if (!animatedCoder) {
return nil;
}
UIImage *image = [animatedCoder animatedImageFrameAtIndex:0];
if (!image) {
return nil;
}
#if SD_MAC
self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:kCGImagePropertyOrientationUp];
#else
self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation];
#endif
if (self) {
// Only keep the animated coder if frame count > 1, save RAM usage for non-animated image format (APNG/WebP)
if (animatedCoder.animatedImageFrameCount > 1) {
_animatedCoder = animatedCoder;
}
}
return self;
}
- (SDImageFormat)animatedImageFormat {
return [NSData sd_imageFormatForImageData:self.animatedImageData];
}
#pragma mark - Preload
- (void)preloadAllFrames {
if (!_animatedCoder) {
return;
}
if (!self.isAllFramesLoaded) {
NSMutableArray<SDImageFrame *> *frames = [NSMutableArray arrayWithCapacity:self.animatedImageFrameCount];
for (size_t i = 0; i < self.animatedImageFrameCount; i++) {
UIImage *image = [self animatedImageFrameAtIndex:i];
NSTimeInterval duration = [self animatedImageDurationAtIndex:i];
SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; // through the image should be nonnull, used as nullable for `animatedImageFrameAtIndex:`
[frames addObject:frame];
}
self.loadedAnimatedImageFrames = frames;
self.allFramesLoaded = YES;
}
}
- (void)unloadAllFrames {
if (!_animatedCoder) {
return;
}
if (self.isAllFramesLoaded) {
self.loadedAnimatedImageFrames = nil;
self.allFramesLoaded = NO;
}
}
#pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
NSData *animatedImageData = [aDecoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(animatedImageData))];
if (!animatedImageData) {
return self;
}
CGFloat scale = self.scale;
id<SDAnimatedImageCoder> animatedCoder = nil;
for (id<SDImageCoder>coder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) {
if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) {
if ([coder canDecodeFromData:animatedImageData]) {
animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:animatedImageData options:@{SDImageCoderDecodeScaleFactor : @(scale)}];
break;
}
}
}
if (!animatedCoder) {
return self;
}
if (animatedCoder.animatedImageFrameCount > 1) {
_animatedCoder = animatedCoder;
}
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
NSData *animatedImageData = self.animatedImageData;
if (animatedImageData) {
[aCoder encodeObject:animatedImageData forKey:NSStringFromSelector(@selector(animatedImageData))];
}
}
+ (BOOL)supportsSecureCoding {
return YES;
}
#pragma mark - SDAnimatedImageProvider
- (NSData *)animatedImageData {
return [self.animatedCoder animatedImageData];
}
- (NSUInteger)animatedImageLoopCount {
return [self.animatedCoder animatedImageLoopCount];
}
- (NSUInteger)animatedImageFrameCount {
return [self.animatedCoder animatedImageFrameCount];
}
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
if (index >= self.animatedImageFrameCount) {
return nil;
}
if (self.isAllFramesLoaded) {
SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index];
return frame.image;
}
return [self.animatedCoder animatedImageFrameAtIndex:index];
}
- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
if (index >= self.animatedImageFrameCount) {
return 0;
}
if (self.isAllFramesLoaded) {
SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index];
return frame.duration;
}
return [self.animatedCoder animatedImageDurationAtIndex:index];
}
@end
@implementation SDAnimatedImage (MemoryCacheCost)
- (NSUInteger)sd_memoryCost {
NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost));
if (value != nil) {
return value.unsignedIntegerValue;
}
CGImageRef imageRef = self.CGImage;
if (!imageRef) {
return 0;
}
NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef);
NSUInteger frameCount = 1;
if (self.isAllFramesLoaded) {
frameCount = self.animatedImageFrameCount;
}
frameCount = frameCount > 0 ? frameCount : 1;
NSUInteger cost = bytesPerFrame * frameCount;
return cost;
}
@end
@implementation SDAnimatedImage (Metadata)
- (BOOL)sd_isAnimated {
return self.animatedImageFrameCount > 1;
}
- (NSUInteger)sd_imageLoopCount {
return self.animatedImageLoopCount;
}
- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount {
return;
}
- (NSUInteger)sd_imageFrameCount {
NSUInteger frameCount = self.animatedImageFrameCount;
if (frameCount > 1) {
return frameCount;
} else {
return 1;
}
}
- (SDImageFormat)sd_imageFormat {
NSData *animatedImageData = self.animatedImageData;
if (animatedImageData) {
return [NSData sd_imageFormatForImageData:animatedImageData];
} else {
return [super sd_imageFormat];
}
}
- (BOOL)sd_isVector {
return NO;
}
@end
@implementation SDAnimatedImage (MultiFormat)
+ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data {
return [self sd_imageWithData:data scale:1];
}
+ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale {
return [self sd_imageWithData:data scale:scale firstFrameOnly:NO];
}
+ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly {
if (!data) {
return nil;
}
return [[self alloc] initWithData:data scale:scale options:@{SDImageCoderDecodeFirstFrameOnly : @(firstFrameOnly)}];
}
- (nullable NSData *)sd_imageData {
NSData *imageData = self.animatedImageData;
if (imageData) {
return imageData;
} else {
return [self sd_imageDataAsFormat:self.animatedImageFormat];
}
}
- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat {
return [self sd_imageDataAsFormat:imageFormat compressionQuality:1];
}
- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality {
return [self sd_imageDataAsFormat:imageFormat compressionQuality:compressionQuality firstFrameOnly:NO];
}
- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly {
// Protect when user input the imageFormat == self.animatedImageFormat && compressionQuality == 1
// This should be treated as grabbing `self.animatedImageData` as well :)
NSData *imageData;
if (imageFormat == self.animatedImageFormat && compressionQuality == 1) {
imageData = self.animatedImageData;
}
if (imageData) return imageData;
SDImageCoderOptions *options = @{SDImageCoderEncodeCompressionQuality : @(compressionQuality), SDImageCoderEncodeFirstFrameOnly : @(firstFrameOnly)};
NSUInteger frameCount = self.animatedImageFrameCount;
if (frameCount <= 1) {
// Static image
imageData = [SDImageCodersManager.sharedManager encodedDataWithImage:self format:imageFormat options:options];
}
if (imageData) return imageData;
NSUInteger loopCount = self.animatedImageLoopCount;
// Keep animated image encoding, loop each frame.
NSMutableArray<SDImageFrame *> *frames = [NSMutableArray arrayWithCapacity:frameCount];
for (size_t i = 0; i < frameCount; i++) {
UIImage *image = [self animatedImageFrameAtIndex:i];
NSTimeInterval duration = [self animatedImageDurationAtIndex:i];
SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration];
[frames addObject:frame];
}
imageData = [SDImageCodersManager.sharedManager encodedDataWithFrames:frames loopCount:loopCount format:imageFormat options:options];
return imageData;
}
@end

View File

@@ -0,0 +1,113 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDImageCoder.h"
/// Animated image playback mode
typedef NS_ENUM(NSUInteger, SDAnimatedImagePlaybackMode) {
/**
* From first to last frame and stop or next loop.
*/
SDAnimatedImagePlaybackModeNormal = 0,
/**
* From last frame to first frame and stop or next loop.
*/
SDAnimatedImagePlaybackModeReverse,
/**
* From first frame to last frame and reverse again, like reciprocating.
*/
SDAnimatedImagePlaybackModeBounce,
/**
* From last frame to first frame and reverse again, like reversed reciprocating.
*/
SDAnimatedImagePlaybackModeReversedBounce,
};
/// A player to control the playback of animated image, which can be used to drive Animated ImageView or any rendering usage, like CALayer/WatchKit/SwiftUI rendering.
@interface SDAnimatedImagePlayer : NSObject
/// Current playing frame image. This value is KVO Compliance.
@property (nonatomic, readonly, nullable) UIImage *currentFrame;
/// Current frame index, zero based. This value is KVO Compliance.
@property (nonatomic, readonly) NSUInteger currentFrameIndex;
/// Current loop count since its latest animating. This value is KVO Compliance.
@property (nonatomic, readonly) NSUInteger currentLoopCount;
/// Total frame count for animated image rendering. Defaults is animated image's frame count.
/// @note For progressive animation, you can update this value when your provider receive more frames.
@property (nonatomic, assign) NSUInteger totalFrameCount;
/// Total loop count for animated image rendering. Default is animated image's loop count.
@property (nonatomic, assign) NSUInteger totalLoopCount;
/// The animation playback rate. Default is 1.0
/// `1.0` means the normal speed.
/// `0.0` means stopping the animation.
/// `0.0-1.0` means the slow speed.
/// `> 1.0` means the fast speed.
/// `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future)
@property (nonatomic, assign) double playbackRate;
/// Asynchronous setup animation playback mode. Default mode is SDAnimatedImagePlaybackModeNormal.
@property (nonatomic, assign) SDAnimatedImagePlaybackMode playbackMode;
/// Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0.
/// `0` means automatically adjust by calculating current memory usage.
/// `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU)
/// `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory)
@property (nonatomic, assign) NSUInteger maxBufferSize;
/// You can specify a runloop mode to let it rendering.
/// Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device
@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode;
/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil.
/// The provider can be any protocol implementation, like `SDAnimatedImage`, `SDImageGIFCoder`, etc.
/// @note This provider can represent mutable content, like progressive animated loading. But you need to update the frame count by yourself
/// @param provider The animated provider
- (nullable instancetype)initWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil.
/// The provider can be any protocol implementation, like `SDAnimatedImage` or `SDImageGIFCoder`, etc.
/// @note This provider can represent mutable content, like progressive animated loading. But you need to update the frame count by yourself
/// @param provider The animated provider
+ (nullable instancetype)playerWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
/// The handler block when current frame and index changed.
@property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame);
/// The handler block when one loop count finished.
@property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount);
/// Return the status whether animation is playing.
@property (nonatomic, readonly) BOOL isPlaying;
/// Start the animation. Or resume the previously paused animation.
- (void)startPlaying;
/// Pause the animation. Keep the current frame index and loop count.
- (void)pausePlaying;
/// Stop the animation. Reset the current frame index and loop count.
- (void)stopPlaying;
/// Seek to the desired frame index and loop count.
/// @note This can be used for advanced control like progressive loading, or skipping specify frames.
/// @param index The frame index
/// @param loopCount The loop count
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount;
/// Clear the frame cache buffer. The frame cache buffer size can be controlled by `maxBufferSize`.
/// By default, when stop or pause the animation, the frame buffer is still kept to ready for the next restart
- (void)clearFrameBuffer;
@end

View File

@@ -0,0 +1,355 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImagePlayer.h"
#import "NSImage+Compatibility.h"
#import "SDDisplayLink.h"
#import "SDDeviceHelper.h"
#import "SDImageFramePool.h"
#import "SDInternalMacros.h"
@interface SDAnimatedImagePlayer () {
NSRunLoopMode _runLoopMode;
}
@property (nonatomic, strong) SDImageFramePool *framePool;
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
@property (nonatomic, strong) id<SDAnimatedImageProvider> animatedProvider;
@property (nonatomic, assign) NSUInteger currentFrameBytes;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, assign) BOOL bufferMiss;
@property (nonatomic, assign) BOOL needsDisplayWhenImageBecomesAvailable;
@property (nonatomic, assign) BOOL shouldReverse;
@property (nonatomic, strong) SDDisplayLink *displayLink;
@end
@implementation SDAnimatedImagePlayer
- (instancetype)initWithProvider:(id<SDAnimatedImageProvider>)provider {
self = [super init];
if (self) {
NSUInteger animatedImageFrameCount = provider.animatedImageFrameCount;
// Check the frame count
if (animatedImageFrameCount <= 1) {
return nil;
}
self.totalFrameCount = animatedImageFrameCount;
// Get the current frame and loop count.
self.totalLoopCount = provider.animatedImageLoopCount;
self.animatedProvider = provider;
self.playbackRate = 1.0;
self.framePool = [SDImageFramePool registerProvider:provider];
}
return self;
}
+ (instancetype)playerWithProvider:(id<SDAnimatedImageProvider>)provider {
SDAnimatedImagePlayer *player = [[SDAnimatedImagePlayer alloc] initWithProvider:provider];
return player;
}
- (void)dealloc {
// Dereference the frame pool, when zero the frame pool for provider will dealloc
[SDImageFramePool unregisterProvider:self.animatedProvider];
}
#pragma mark - Private
- (SDDisplayLink *)displayLink {
if (!_displayLink) {
_displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)];
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
[_displayLink stop];
}
return _displayLink;
}
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode {
if ([_runLoopMode isEqual:runLoopMode]) {
return;
}
if (_displayLink) {
if (_runLoopMode) {
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode];
}
if (runLoopMode.length > 0) {
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode];
}
}
_runLoopMode = [runLoopMode copy];
}
- (NSRunLoopMode)runLoopMode {
if (!_runLoopMode) {
_runLoopMode = [[self class] defaultRunLoopMode];
}
return _runLoopMode;
}
#pragma mark - State Control
- (void)setupCurrentFrame {
if (self.currentFrameIndex != 0) {
return;
}
if (self.playbackMode == SDAnimatedImagePlaybackModeReverse ||
self.playbackMode == SDAnimatedImagePlaybackModeReversedBounce) {
self.currentFrameIndex = self.totalFrameCount - 1;
}
if (!self.currentFrame && [self.animatedProvider isKindOfClass:[UIImage class]]) {
UIImage *image = (UIImage *)self.animatedProvider;
// Cache the poster image if available, but should not callback to avoid caller thread issues
#if SD_MAC
UIImage *posterFrame = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp];
#else
UIImage *posterFrame = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];
#endif
if (posterFrame) {
// Calculate max buffer size
[self calculateMaxBufferCountWithFrame:posterFrame];
// HACK: The first frame should not check duration and immediately display
self.needsDisplayWhenImageBecomesAvailable = YES;
[self.framePool setFrame:posterFrame atIndex:self.currentFrameIndex];
}
}
}
- (void)resetCurrentFrameStatus {
// These should not trigger KVO, user don't need to receive an `index == 0, image == nil` callback.
_currentFrame = nil;
_currentFrameIndex = 0;
_currentLoopCount = 0;
_currentTime = 0;
_bufferMiss = NO;
_needsDisplayWhenImageBecomesAvailable = NO;
}
- (void)clearFrameBuffer {
[self.framePool removeAllFrames];
}
#pragma mark - Animation Control
- (void)startPlaying {
[self.displayLink start];
// Setup frame
[self setupCurrentFrame];
}
- (void)stopPlaying {
// Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method.
[_displayLink stop];
// We need to reset the frame status, but not trigger any handle. This can ensure next time's playing status correct.
[self resetCurrentFrameStatus];
}
- (void)pausePlaying {
[_displayLink stop];
}
- (BOOL)isPlaying {
return _displayLink.isRunning;
}
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount {
if (index >= self.totalFrameCount) {
return;
}
self.currentFrameIndex = index;
self.currentLoopCount = loopCount;
self.currentFrame = [self.animatedProvider animatedImageFrameAtIndex:index];
[self handleFrameChange];
}
#pragma mark - Core Render
- (void)displayDidRefresh:(SDDisplayLink *)displayLink {
// If for some reason a wild call makes it through when we shouldn't be animating, bail.
// Early return!
if (!self.isPlaying) {
return;
}
NSUInteger totalFrameCount = self.totalFrameCount;
if (totalFrameCount <= 1) {
// Total frame count less than 1, wrong configuration and stop animating
[self stopPlaying];
return;
}
NSTimeInterval playbackRate = self.playbackRate;
if (playbackRate <= 0) {
// Does not support <= 0 play rate
[self stopPlaying];
return;
}
// Calculate refresh duration
NSTimeInterval duration = self.displayLink.duration;
NSUInteger currentFrameIndex = self.currentFrameIndex;
NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount;
if (self.playbackMode == SDAnimatedImagePlaybackModeReverse) {
nextFrameIndex = currentFrameIndex == 0 ? (totalFrameCount - 1) : (currentFrameIndex - 1) % totalFrameCount;
} else if (self.playbackMode == SDAnimatedImagePlaybackModeBounce ||
self.playbackMode == SDAnimatedImagePlaybackModeReversedBounce) {
if (currentFrameIndex == 0) {
self.shouldReverse = NO;
} else if (currentFrameIndex == totalFrameCount - 1) {
self.shouldReverse = YES;
}
nextFrameIndex = self.shouldReverse ? (currentFrameIndex - 1) : (currentFrameIndex + 1);
nextFrameIndex %= totalFrameCount;
}
// Check if we need to display new frame firstly
if (self.needsDisplayWhenImageBecomesAvailable) {
UIImage *currentFrame = [self.framePool frameAtIndex:currentFrameIndex];
// Update the current frame
if (currentFrame) {
// Update the current frame immediately
self.currentFrame = currentFrame;
[self handleFrameChange];
self.bufferMiss = NO;
self.needsDisplayWhenImageBecomesAvailable = NO;
}
else {
self.bufferMiss = YES;
}
}
// Check if we have the frame buffer
if (!self.bufferMiss) {
// Then check if timestamp is reached
self.currentTime += duration;
NSTimeInterval currentDuration = [self.animatedProvider animatedImageDurationAtIndex:currentFrameIndex];
currentDuration = currentDuration / playbackRate;
if (self.currentTime < currentDuration) {
// Current frame timestamp not reached, prefetch frame in advance.
[self prefetchFrameAtIndex:currentFrameIndex
nextIndex:nextFrameIndex];
return;
}
// Otherwise, we should be ready to display next frame
self.needsDisplayWhenImageBecomesAvailable = YES;
self.currentFrameIndex = nextFrameIndex;
self.currentTime -= currentDuration;
NSTimeInterval nextDuration = [self.animatedProvider animatedImageDurationAtIndex:nextFrameIndex];
nextDuration = nextDuration / playbackRate;
if (self.currentTime > nextDuration) {
// Do not skip frame
self.currentTime = nextDuration;
}
// Update the loop count when last frame rendered
if (nextFrameIndex == 0) {
// Update the loop count
self.currentLoopCount++;
[self handleLoopChange];
// if reached the max loop count, stop animating, 0 means loop indefinitely
NSUInteger maxLoopCount = self.totalLoopCount;
if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) {
[self stopPlaying];
return;
}
}
}
// Since we support handler, check animating state again
if (!self.isPlaying) {
return;
}
[self prefetchFrameAtIndex:currentFrameIndex
nextIndex:nextFrameIndex];
}
// Check if we should prefetch next frame or current frame
// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame
// Or, most cases, the decode speed is faster than render speed, we fetch next frame
- (void)prefetchFrameAtIndex:(NSUInteger)currentIndex
nextIndex:(NSUInteger)nextIndex {
NSUInteger fetchFrameIndex = currentIndex;
UIImage *fetchFrame = nil;
if (!self.bufferMiss) {
fetchFrameIndex = nextIndex;
fetchFrame = [self.framePool frameAtIndex:nextIndex];
}
BOOL bufferFull = NO;
if (self.framePool.currentFrameCount == self.totalFrameCount) {
bufferFull = YES;
}
if (!fetchFrame && !bufferFull) {
// Calculate max buffer size
[self calculateMaxBufferCountWithFrame:self.currentFrame];
// Prefetch next frame
[self.framePool prefetchFrameAtIndex:fetchFrameIndex];
}
}
- (void)handleFrameChange {
if (self.animationFrameHandler) {
self.animationFrameHandler(self.currentFrameIndex, self.currentFrame);
}
}
- (void)handleLoopChange {
if (self.animationLoopHandler) {
self.animationLoopHandler(self.currentLoopCount);
}
}
#pragma mark - Util
- (void)calculateMaxBufferCountWithFrame:(nonnull UIImage *)frame {
NSUInteger bytes = self.currentFrameBytes;
if (bytes == 0) {
bytes = CGImageGetBytesPerRow(frame.CGImage) * CGImageGetHeight(frame.CGImage);
if (bytes == 0) {
bytes = 1024;
} else {
// Cache since most animated image each frame bytes is the same
self.currentFrameBytes = bytes;
}
}
NSUInteger max = 0;
if (self.maxBufferSize > 0) {
max = self.maxBufferSize;
} else {
// Calculate based on current memory, these factors are by experience
NSUInteger total = [SDDeviceHelper totalMemory];
NSUInteger free = [SDDeviceHelper freeMemory];
max = MIN(total * 0.2, free * 0.6);
}
NSUInteger maxBufferCount = (double)max / (double)bytes;
if (!maxBufferCount) {
// At least 1 frame
maxBufferCount = 1;
}
self.framePool.maxBufferCount = maxBufferCount;
}
+ (NSString *)defaultRunLoopMode {
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
}
@end

View File

@@ -0,0 +1,33 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_MAC
#import "NSData+ImageContentType.h"
/**
A subclass of `NSBitmapImageRep` to fix that GIF duration issue because `NSBitmapImageRep` will reset `NSImageCurrentFrameDuration` by using `kCGImagePropertyGIFDelayTime` but not `kCGImagePropertyGIFUnclampedDelayTime`.
This also fix the GIF loop count issue, which will use the Netscape standard (See http://www6.uniovi.es/gifanim/gifabout.htm) to only place once when the `kCGImagePropertyGIFLoopCount` is nil. This is what modern browser's behavior.
Built in GIF coder use this instead of `NSBitmapImageRep` for better GIF rendering. If you do not want this, only enable `SDImageIOCoder`, which just call `NSImage` API and actually use `NSBitmapImageRep` for GIF image.
This also support APNG format using `SDImageAPNGCoder`. Which provide full alpha-channel support and the correct duration match the `kCGImagePropertyAPNGUnclampedDelayTime`.
*/
@interface SDAnimatedImageRep : NSBitmapImageRep
/// Current animated image format.
/// @note This format is only valid when `animatedImageData` not nil
@property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat;
/// This allows to retrive the compressed data like GIF using `sd_imageData` on parent `NSImage`, without re-encoding (waste CPU and RAM)
/// @note This is typically nonnull when you create with `initWithData:`, even it's marked as weak, because ImageIO retain it
@property (nonatomic, readonly, nullable, weak) NSData *animatedImageData;
@end
#endif

View File

@@ -0,0 +1,151 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImageRep.h"
#if SD_MAC
#import "SDImageIOAnimatedCoderInternal.h"
#import "SDImageGIFCoder.h"
#import "SDImageAPNGCoder.h"
#import "SDImageHEICCoder.h"
#import "SDImageAWebPCoder.h"
@interface SDAnimatedImageRep ()
/// This wrap the animated image frames for legacy animated image coder API (`encodedDataWithImage:`).
@property (nonatomic, readwrite, weak) NSArray<SDImageFrame *> *frames;
@property (nonatomic, assign, readwrite) SDImageFormat animatedImageFormat;
@end
@implementation SDAnimatedImageRep {
CGImageSourceRef _imageSource;
}
- (void)dealloc {
if (_imageSource) {
CFRelease(_imageSource);
_imageSource = NULL;
}
}
- (instancetype)copyWithZone:(NSZone *)zone {
SDAnimatedImageRep *imageRep = [super copyWithZone:zone];
// super will copy all ivars
if (imageRep->_imageSource) {
CFRetain(imageRep->_imageSource);
}
return imageRep;
}
// `NSBitmapImageRep`'s `imageRepWithData:` is not designed initializer
+ (instancetype)imageRepWithData:(NSData *)data {
SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data];
return imageRep;
}
// We should override init method for `NSBitmapImageRep` to do initialize about animated image format
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
- (instancetype)initWithData:(NSData *)data {
self = [super initWithData:data];
if (self) {
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef) data, NULL);
if (!imageSource) {
return self;
}
_imageSource = imageSource;
NSUInteger frameCount = CGImageSourceGetCount(imageSource);
if (frameCount <= 1) {
return self;
}
CFStringRef type = CGImageSourceGetType(imageSource);
if (!type) {
return self;
}
_animatedImageData = data; // CGImageSource will retain the data internally, no extra copy
SDImageFormat format = SDImageFormatUndefined;
if (CFStringCompare(type, kSDUTTypeGIF, 0) == kCFCompareEqualTo) {
// GIF
// Fix the `NSBitmapImageRep` GIF loop count calculation issue
// Which will use 0 when there are no loop count information metadata in GIF data
format = SDImageFormatGIF;
NSUInteger loopCount = [SDImageGIFCoder imageLoopCountWithSource:imageSource];
[self setProperty:NSImageLoopCount withValue:@(loopCount)];
} else if (CFStringCompare(type, kSDUTTypePNG, 0) == kCFCompareEqualTo) {
// APNG
// Do initialize about frame count, current frame/duration and loop count
format = SDImageFormatPNG;
[self setProperty:NSImageFrameCount withValue:@(frameCount)];
[self setProperty:NSImageCurrentFrame withValue:@(0)];
NSUInteger loopCount = [SDImageAPNGCoder imageLoopCountWithSource:imageSource];
[self setProperty:NSImageLoopCount withValue:@(loopCount)];
} else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) {
// HEIC
// Do initialize about frame count, current frame/duration and loop count
format = SDImageFormatHEIC;
[self setProperty:NSImageFrameCount withValue:@(frameCount)];
[self setProperty:NSImageCurrentFrame withValue:@(0)];
NSUInteger loopCount = [SDImageHEICCoder imageLoopCountWithSource:imageSource];
[self setProperty:NSImageLoopCount withValue:@(loopCount)];
} else if (CFStringCompare(type, kSDUTTypeWebP, 0) == kCFCompareEqualTo) {
// WebP
// Do initialize about frame count, current frame/duration and loop count
format = SDImageFormatWebP;
[self setProperty:NSImageFrameCount withValue:@(frameCount)];
[self setProperty:NSImageCurrentFrame withValue:@(0)];
NSUInteger loopCount = [SDImageAWebPCoder imageLoopCountWithSource:imageSource];
[self setProperty:NSImageLoopCount withValue:@(loopCount)];
} else {
format = [NSData sd_imageFormatForImageData:data];
}
_animatedImageFormat = format;
}
return self;
}
// `NSBitmapImageRep` will use `kCGImagePropertyGIFDelayTime` whenever you call `setProperty:withValue:` with `NSImageCurrentFrame` to change the current frame. We override it and use the actual `kCGImagePropertyGIFUnclampedDelayTime` if need.
- (void)setProperty:(NSBitmapImageRepPropertyKey)property withValue:(id)value {
[super setProperty:property withValue:value];
if ([property isEqualToString:NSImageCurrentFrame]) {
// Access the image source
CGImageSourceRef imageSource = _imageSource;
if (!imageSource) {
return;
}
// Check format type
CFStringRef type = CGImageSourceGetType(imageSource);
if (!type) {
return;
}
NSUInteger index = [value unsignedIntegerValue];
NSTimeInterval frameDuration = 0;
if (CFStringCompare(type, kSDUTTypeGIF, 0) == kCFCompareEqualTo) {
// GIF
frameDuration = [SDImageGIFCoder frameDurationAtIndex:index source:imageSource];
} else if (CFStringCompare(type, kSDUTTypePNG, 0) == kCFCompareEqualTo) {
// APNG
frameDuration = [SDImageAPNGCoder frameDurationAtIndex:index source:imageSource];
} else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) {
// HEIC
frameDuration = [SDImageHEICCoder frameDurationAtIndex:index source:imageSource];
} else if (CFStringCompare(type, kSDUTTypeWebP, 0) == kCFCompareEqualTo) {
// WebP
frameDuration = [SDImageAWebPCoder frameDurationAtIndex:index source:imageSource];
}
if (!frameDuration) {
return;
}
// Reset super frame duration with the actual frame duration
[super setProperty:NSImageCurrentFrameDuration withValue:@(frameDuration)];
}
}
#pragma clang diagnostic pop
@end
#endif

View File

@@ -0,0 +1,168 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImageView.h"
#if SD_UIKIT || SD_MAC
#import "SDWebImageManager.h"
/**
Integrates SDWebImage async downloading and caching of remote images with SDAnimatedImageView.
*/
@interface SDAnimatedImageView (WebCache)
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `image` with an `url` and a placeholder.
*
* The download 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 sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download 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)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `image` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download 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
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
@end
#endif

View File

@@ -0,0 +1,79 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImageView+WebCache.h"
#if SD_UIKIT || SD_MAC
#import "UIView+WebCache.h"
#import "SDAnimatedImage.h"
@implementation SDAnimatedImageView (WebCache)
- (void)sd_setImageWithURL:(nullable NSURL *)url {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
Class animatedImageClass = [SDAnimatedImage class];
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
mutableContext[SDWebImageContextAnimatedImageClass] = animatedImageClass;
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
context:mutableContext
setImageBlock:nil
progress:progressBlock
completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageURL);
}
}];
}
@end
#endif

View File

@@ -0,0 +1,125 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_UIKIT || SD_MAC
#import "SDAnimatedImage.h"
#import "SDAnimatedImagePlayer.h"
#import "SDImageTransformer.h"
/**
A drop-in replacement for UIImageView/NSImageView, you can use this for animated image rendering.
Call `setImage:` with `UIImage(NSImage)` which conforms to `SDAnimatedImage` protocol will start animated image rendering. Call with normal UIImage(NSImage) will back to normal UIImageView(NSImageView) rendering
For UIKit: use `-startAnimating`, `-stopAnimating` to control animating. `isAnimating` to check animation state.
For AppKit: use `-setAnimates:` to control animating, `animates` to check animation state. This view is layer-backed.
*/
NS_SWIFT_UI_ACTOR
@interface SDAnimatedImageView : UIImageView
/**
The internal animation player.
This property is only used for advanced usage, like inspecting/debugging animation status, control progressive loading, complicated animation frame index control, etc.
@warning Pay attention if you directly update the player's property like `totalFrameCount`, `totalLoopCount`, the same property on `SDAnimatedImageView` may not get synced.
*/
@property (nonatomic, strong, readonly, nullable) SDAnimatedImagePlayer *player;
/**
The transformer for each decoded animated image frame.
We supports post-transform on animated image frame from version 5.20.
When you configure the transformer on `SDAnimatedImageView` and animation is playing, the `transformedImageWithImage:forKey:` will be called just after the frame is decoded. (note: The `key` arg is always empty for backward-compatible and may be removed in the future)
Example to tint the alpha animated image frame with a black color:
* @code
imageView.animationTransformer = [SDImageTintTransformer transformerWithColor:UIColor.blackColor];
* @endcode
@note The `transformerKey` property is used to ensure the buffer cache available. So make sure it's correct value match the actual logic on transformer. Which means, for the `same frame index + same transformer key`, the transformed image should always be the same.
*/
@property (nonatomic, strong, nullable) id<SDImageTransformer> animationTransformer;
/**
Current display frame image. This value is KVO Compliance.
*/
@property (nonatomic, strong, readonly, nullable) UIImage *currentFrame;
/**
Current frame index, zero based. This value is KVO Compliance.
*/
@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex;
/**
Current loop count since its latest animating. This value is KVO Compliance.
*/
@property (nonatomic, assign, readonly) NSUInteger currentLoopCount;
/**
YES to choose `animationRepeatCount` property for animation loop count. No to use animated image's `animatedImageLoopCount` instead.
Default is NO.
*/
@property (nonatomic, assign) BOOL shouldCustomLoopCount;
/**
Total loop count for animated image rendering. Default is animated image's loop count.
If you need to set custom loop count, set `shouldCustomLoopCount` to YES and change this value.
This class override UIImageView's `animationRepeatCount` property on iOS, use this property as well.
*/
@property (nonatomic, assign) NSInteger animationRepeatCount;
/**
The animation playback rate. Default is 1.0.
`1.0` means the normal speed.
`0.0` means stopping the animation.
`0.0-1.0` means the slow speed.
`> 1.0` means the fast speed.
`< 0.0` is not supported currently and stop animation. (may support reverse playback in the future)
*/
@property (nonatomic, assign) double playbackRate;
/// Asynchronous setup animation playback mode. Default mode is SDAnimatedImagePlaybackModeNormal.
@property (nonatomic, assign) SDAnimatedImagePlaybackMode playbackMode;
/**
Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0.
`0` means automatically adjust by calculating current memory usage.
`1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU)
`NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory)
*/
@property (nonatomic, assign) NSUInteger maxBufferSize;
/**
Whehter or not to enable incremental image load for animated image. This is for the animated image which `sd_isIncremental` is YES (See `UIImage+Metadata.h`). If enable, animated image rendering will stop at the last frame available currently, and continue when another `setImage:` trigger, where the new animated image's `animatedImageData` should be updated from the previous one. If the `sd_isIncremental` is NO. The incremental image load stop.
@note If you are confused about this description, open Chrome browser to view some large GIF images with low network speed to see the animation behavior.
@note The best practice to use incremental load is using `initWithAnimatedCoder:scale:` in `SDAnimatedImage` with animated coder which conform to `SDProgressiveImageCoder` as well. Then call incremental update and incremental decode method to produce the image.
Default is YES. Set to NO to only render the static poster for incremental animated image.
*/
@property (nonatomic, assign) BOOL shouldIncrementalLoad;
/**
Whether or not to clear the frame buffer cache when animation stopped. See `maxBufferSize`
This is useful when you want to limit the memory usage during frequently visibility changes (such as image view inside a list view, then push and pop)
Default is NO.
*/
@property (nonatomic, assign) BOOL clearBufferWhenStopped;
/**
Whether or not to reset the current frame index when animation stopped.
For some of use case, you may want to reset the frame index to 0 when stop, but some other want to keep the current frame index.
Default is NO.
*/
@property (nonatomic, assign) BOOL resetFrameIndexWhenStopped;
/**
If the image which conforms to `SDAnimatedImage` protocol has more than one frame, set this value to `YES` will automatically
play/stop the animation when the view become visible/invisible.
Default is YES.
*/
@property (nonatomic, assign) BOOL autoPlayAnimatedImage;
/**
You can specify a runloop mode to let it rendering.
Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device
@note This is useful for some cases, for example, always specify NSDefaultRunLoopMode, if you want to pause the animation when user scroll (for Mac user, drag the mouse or touchpad)
*/
@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode;
@end
#endif

View File

@@ -0,0 +1,622 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImageView.h"
#if SD_UIKIT || SD_MAC
#import "UIImage+Metadata.h"
#import "NSImage+Compatibility.h"
#import "SDInternalMacros.h"
#import "objc/runtime.h"
// A wrapper to implements the transformer on animated image, like tint color
@interface SDAnimatedImageFrameProvider : NSObject <SDAnimatedImageProvider>
@property (nonatomic, strong) id<SDAnimatedImageProvider> provider;
@property (nonatomic, strong) id<SDImageTransformer> transformer;
@end
@implementation SDAnimatedImageFrameProvider
- (instancetype)initWithProvider:(id<SDAnimatedImageProvider>)provider transformer:(id<SDImageTransformer>)transformer {
self = [super init];
if (self) {
_provider = provider;
_transformer = transformer;
}
return self;
}
- (NSUInteger)hash {
NSUInteger prime = 31;
NSUInteger result = 1;
NSUInteger providerHash = self.provider.hash;
NSUInteger transformerHash = self.transformer.transformerKey.hash;
result = prime * result + providerHash;
result = prime * result + transformerHash;
return result;
}
- (BOOL)isEqual:(id)object {
if (nil == object) {
return NO;
}
if (self == object) {
return YES;
}
if (![object isKindOfClass:[self class]]) {
return NO;
}
return self.provider == [object provider]
&& [self.transformer.transformerKey isEqualToString:[object transformer].transformerKey];
}
- (NSData *)animatedImageData {
return self.provider.animatedImageData;
}
- (NSUInteger)animatedImageFrameCount {
return self.provider.animatedImageFrameCount;
}
- (NSUInteger)animatedImageLoopCount {
return self.provider.animatedImageLoopCount;
}
- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
return [self.provider animatedImageDurationAtIndex:index];
}
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
UIImage *frame = [self.provider animatedImageFrameAtIndex:index];
return [self.transformer transformedImageWithImage:frame forKey:@""];
}
@end
@interface UIImageView () <CALayerDelegate>
@end
@interface SDAnimatedImageView () {
BOOL _initFinished; // Extra flag to mark the `commonInit` is called
NSRunLoopMode _runLoopMode;
NSUInteger _maxBufferSize;
double _playbackRate;
SDAnimatedImagePlaybackMode _playbackMode;
}
@property (nonatomic, strong, readwrite) SDAnimatedImagePlayer *player;
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
@property (nonatomic, assign) BOOL shouldAnimate;
@property (nonatomic, assign) BOOL isProgressive;
@property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer.
@end
@implementation SDAnimatedImageView
#if SD_UIKIT
@dynamic animationRepeatCount; // we re-use this property from `UIImageView` super class on iOS.
#endif
#pragma mark - Initializers
#if SD_MAC
+ (instancetype)imageViewWithImage:(NSImage *)image
{
NSRect frame = NSMakeRect(0, 0, image.size.width, image.size.height);
SDAnimatedImageView *imageView = [[SDAnimatedImageView alloc] initWithFrame:frame];
[imageView setImage:image];
return imageView;
}
#else
// -initWithImage: isn't documented as a designated initializer of UIImageView, but it actually seems to be.
// Using -initWithImage: doesn't call any of the other designated initializers.
- (instancetype)initWithImage:(UIImage *)image
{
self = [super initWithImage:image];
if (self) {
[self commonInit];
}
return self;
}
// -initWithImage:highlightedImage: also isn't documented as a designated initializer of UIImageView, but it doesn't call any other designated initializers.
- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage
{
self = [super initWithImage:image highlightedImage:highlightedImage];
if (self) {
[self commonInit];
}
return self;
}
#endif
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit
{
// Pay attention that UIKit's `initWithImage:` will trigger a `setImage:` during initialization before this `commonInit`.
// So the properties which rely on this order, should using lazy-evaluation or do extra check in `setImage:`.
self.autoPlayAnimatedImage = YES;
self.shouldCustomLoopCount = NO;
self.shouldIncrementalLoad = YES;
self.playbackRate = 1.0;
#if SD_MAC
self.wantsLayer = YES;
#endif
// Mark commonInit finished
_initFinished = YES;
}
#pragma mark - Accessors
#pragma mark Public
- (void)setImage:(UIImage *)image
{
if (self.image == image) {
return;
}
// Check Progressive rendering
[self updateIsProgressiveWithImage:image];
if (!self.isProgressive) {
// Stop animating
self.player = nil;
self.currentFrame = nil;
self.currentFrameIndex = 0;
self.currentLoopCount = 0;
}
// We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end.
super.image = image;
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && [(id<SDAnimatedImage>)image animatedImageFrameCount] > 1) {
if (!self.player) {
id<SDAnimatedImageProvider> provider;
// Check progressive loading
if (self.isProgressive) {
provider = [(id<SDAnimatedImage>)image animatedCoder];
} else {
provider = (id<SDAnimatedImage>)image;
}
// Create animated player
if (self.animationTransformer) {
// Check if post-transform animation available
provider = [[SDAnimatedImageFrameProvider alloc] initWithProvider:provider transformer:self.animationTransformer];
self.player = [SDAnimatedImagePlayer playerWithProvider:provider];
} else {
// Normal animation without post-transform
self.player = [SDAnimatedImagePlayer playerWithProvider:provider];
}
} else {
// Update Frame Count
self.player.totalFrameCount = [(id<SDAnimatedImage>)image animatedImageFrameCount];
}
if (!self.player) {
// animated player nil means the image format is not supported, or frame count <= 1
return;
}
// Custom Loop Count
if (self.shouldCustomLoopCount) {
self.player.totalLoopCount = self.animationRepeatCount;
}
// RunLoop Mode
self.player.runLoopMode = self.runLoopMode;
// Max Buffer Size
self.player.maxBufferSize = self.maxBufferSize;
// Play Rate
self.player.playbackRate = self.playbackRate;
// Play Mode
self.player.playbackMode = self.playbackMode;
// Setup handler
@weakify(self);
self.player.animationFrameHandler = ^(NSUInteger index, UIImage * frame) {
@strongify(self);
self.currentFrameIndex = index;
self.currentFrame = frame;
[self.imageViewLayer setNeedsDisplay];
};
self.player.animationLoopHandler = ^(NSUInteger loopCount) {
@strongify(self);
// Progressive image reach the current last frame index. Keep the state and pause animating. Wait for later restart
if (self.isProgressive) {
NSUInteger lastFrameIndex = self.player.totalFrameCount - 1;
[self.player seekToFrameAtIndex:lastFrameIndex loopCount:0];
[self.player pausePlaying];
} else {
self.currentLoopCount = loopCount;
}
};
// Ensure disabled highlighting; it's not supported (see `-setHighlighted:`).
super.highlighted = NO;
[self stopAnimating];
[self checkPlay];
}
[self.imageViewLayer setNeedsDisplay];
}
#pragma mark - Configuration
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode
{
_runLoopMode = [runLoopMode copy];
self.player.runLoopMode = runLoopMode;
}
- (NSRunLoopMode)runLoopMode
{
if (!_runLoopMode) {
_runLoopMode = [[self class] defaultRunLoopMode];
}
return _runLoopMode;
}
+ (NSString *)defaultRunLoopMode {
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
}
- (void)setMaxBufferSize:(NSUInteger)maxBufferSize
{
_maxBufferSize = maxBufferSize;
self.player.maxBufferSize = maxBufferSize;
}
- (NSUInteger)maxBufferSize {
return _maxBufferSize; // Defaults to 0
}
- (void)setPlaybackRate:(double)playbackRate
{
_playbackRate = playbackRate;
self.player.playbackRate = playbackRate;
}
- (double)playbackRate
{
if (!_initFinished) {
return 1.0; // Defaults to 1.0
}
return _playbackRate;
}
- (void)setPlaybackMode:(SDAnimatedImagePlaybackMode)playbackMode {
_playbackMode = playbackMode;
self.player.playbackMode = playbackMode;
}
- (SDAnimatedImagePlaybackMode)playbackMode {
if (!_initFinished) {
return SDAnimatedImagePlaybackModeNormal; // Default mode is normal
}
return _playbackMode;
}
- (BOOL)shouldIncrementalLoad
{
if (!_initFinished) {
return YES; // Defaults to YES
}
return _initFinished;
}
#pragma mark - UIView Method Overrides
#pragma mark Observing View-Related Changes
#if SD_MAC
- (void)viewDidMoveToSuperview
#else
- (void)didMoveToSuperview
#endif
{
#if SD_MAC
[super viewDidMoveToSuperview];
#else
[super didMoveToSuperview];
#endif
[self checkPlay];
}
#if SD_MAC
- (void)viewDidMoveToWindow
#else
- (void)didMoveToWindow
#endif
{
#if SD_MAC
[super viewDidMoveToWindow];
#else
[super didMoveToWindow];
#endif
[self checkPlay];
}
#if SD_MAC
- (void)setAlphaValue:(CGFloat)alphaValue
#else
- (void)setAlpha:(CGFloat)alpha
#endif
{
#if SD_MAC
[super setAlphaValue:alphaValue];
#else
[super setAlpha:alpha];
#endif
[self checkPlay];
}
- (void)setHidden:(BOOL)hidden
{
[super setHidden:hidden];
[self checkPlay];
}
#pragma mark - UIImageView Method Overrides
#pragma mark Image Data
- (void)setAnimationRepeatCount:(NSInteger)animationRepeatCount
{
#if SD_UIKIT
[super setAnimationRepeatCount:animationRepeatCount];
#else
_animationRepeatCount = animationRepeatCount;
#endif
if (self.shouldCustomLoopCount) {
self.player.totalLoopCount = animationRepeatCount;
}
}
- (void)startAnimating
{
if (self.player) {
[self updateShouldAnimate];
if (self.shouldAnimate) {
[self.player startPlaying];
}
} else {
#if SD_UIKIT
[super startAnimating];
#else
[super setAnimates:YES];
#endif
}
}
- (void)stopAnimating
{
if (self.player) {
if (self.resetFrameIndexWhenStopped) {
[self.player stopPlaying];
} else {
[self.player pausePlaying];
}
if (self.clearBufferWhenStopped) {
[self.player clearFrameBuffer];
}
} else {
#if SD_UIKIT
[super stopAnimating];
#else
[super setAnimates:NO];
#endif
}
}
#if SD_UIKIT
- (BOOL)isAnimating
{
if (self.player) {
return self.player.isPlaying;
} else {
return [super isAnimating];
}
}
#endif
#if SD_MAC
- (BOOL)animates
{
if (self.player) {
return self.player.isPlaying;
} else {
return [super animates];
}
}
- (void)setAnimates:(BOOL)animates
{
if (animates) {
[self startAnimating];
} else {
[self stopAnimating];
}
}
#endif
#pragma mark Highlighted Image Unsupport
- (void)setHighlighted:(BOOL)highlighted
{
// Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell.
if (!self.player) {
[super setHighlighted:highlighted];
}
}
#pragma mark - Private Methods
#pragma mark Animation
/// Check if it should be played
- (void)checkPlay
{
// Only handle for SDAnimatedImage, leave UIAnimatedImage or animationImages for super implementation control
if (self.player && self.autoPlayAnimatedImage) {
[self updateShouldAnimate];
if (self.shouldAnimate) {
[self startAnimating];
} else {
[self stopAnimating];
}
}
}
// Don't repeatedly check our window & superview in `-displayDidRefresh:` for performance reasons.
// Just update our cached value whenever the animated image or visibility (window, superview, hidden, alpha) is changed.
- (void)updateShouldAnimate
{
#if SD_MAC
BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alphaValue > 0.0;
#else
BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0;
#endif
self.shouldAnimate = self.player && isVisible;
}
// Update progressive status only after `setImage:` call.
- (void)updateIsProgressiveWithImage:(UIImage *)image
{
self.isProgressive = NO;
if (!self.shouldIncrementalLoad) {
// Early return
return;
}
// We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here
// Because UIKit on macOS, using internal hard-coded override method, which returns NO
id<SDAnimatedImageCoder> currentAnimatedCoder = [self progressiveAnimatedCoderForImage:image];
if (currentAnimatedCoder) {
UIImage *previousImage = self.image;
if (!previousImage) {
// If current animated coder supports progressive, and no previous image to check, start progressive loading
self.isProgressive = YES;
} else {
id<SDAnimatedImageCoder> previousAnimatedCoder = [self progressiveAnimatedCoderForImage:previousImage];
if (previousAnimatedCoder == currentAnimatedCoder) {
// If current animated coder is the same as previous, start progressive loading
self.isProgressive = YES;
}
}
}
}
// Check if image can represent a `Progressive Animated Image` during loading
- (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)progressiveAnimatedCoderForImage:(UIImage *)image
{
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental && [image respondsToSelector:@selector(animatedCoder)]) {
id<SDAnimatedImageCoder> animatedCoder = [(id<SDAnimatedImage>)image animatedCoder];
if ([animatedCoder respondsToSelector:@selector(initIncrementalWithOptions:)]) {
return (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)animatedCoder;
}
}
return nil;
}
#pragma mark Providing the Layer's Content
#pragma mark - CALayerDelegate
- (void)displayLayer:(CALayer *)layer
{
UIImage *currentFrame = self.currentFrame;
if (currentFrame) {
layer.contentsScale = currentFrame.scale;
layer.contents = (__bridge id)currentFrame.CGImage;
} else {
// If we have no animation frames, call super implementation. iOS 14+ UIImageView use this delegate method for rendering.
if ([UIImageView instancesRespondToSelector:@selector(displayLayer:)]) {
[super displayLayer:layer];
} else {
// Fallback to implements the static image rendering by ourselves (like macOS or before iOS 14)
currentFrame = super.image;
layer.contentsScale = currentFrame.scale;
layer.contents = (__bridge id)currentFrame.CGImage;
}
}
}
#if SD_UIKIT
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
// See: #3635
// From iOS 17, when UIImageView entering the background, it will receive the trait collection changes, and modify the CALayer.contents by `self.image.CGImage`
// However, For animated image, `self.image.CGImge != self.currentFrame.CGImage`, right ?
// So this cause the render issue, we need to reset the CALayer.contents again
[super traitCollectionDidChange:previousTraitCollection];
[self.imageViewLayer setNeedsDisplay];
}
#endif
#if SD_MAC
// NSImageView use a subview. We need this subview's layer for actual rendering.
// Why using this design may because of properties like `imageAlignment` and `imageScaling`, which it's not available for UIImageView.contentMode (it's impossible to align left and keep aspect ratio at the same time)
- (NSView *)imageView {
NSImageView *imageView = objc_getAssociatedObject(self, SD_SEL_SPI(imageView));
if (!imageView) {
// macOS 10.14
imageView = objc_getAssociatedObject(self, SD_SEL_SPI(imageSubview));
}
return imageView;
}
// on macOS, it's the imageView subview's layer (we use layer-hosting view to let CALayerDelegate works)
- (CALayer *)imageViewLayer {
NSView *imageView = self.imageView;
if (!imageView) {
return nil;
}
if (!_imageViewLayer) {
_imageViewLayer = [CALayer new];
_imageViewLayer.delegate = self;
imageView.layer = _imageViewLayer;
imageView.wantsLayer = YES;
}
return _imageViewLayer;
}
#else
// on iOS, it's the imageView itself's layer
- (CALayer *)imageViewLayer {
return self.layer;
}
#endif
@end
#endif

View File

@@ -0,0 +1,59 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
/// SDCallbackPolicy controls how we execute the block on the queue, like whether to use `dispatch_async/dispatch_sync`, check if current queue match target queue, or just invoke without any context.
typedef NS_ENUM(NSUInteger, SDCallbackPolicy) {
/// When the current queue is equal to callback queue, sync/async will just invoke `block` directly without dispatch. Else it use `dispatch_async`/`dispatch_sync` to dispatch block on queue. This is useful for UIKit rendering to ensure all blocks executed in the same runloop
SDCallbackPolicySafeExecute = 0,
/// Follow async/sync using the correspond `dispatch_async`/`dispatch_sync` to dispatch block on queue
SDCallbackPolicyDispatch = 1,
/// Ignore any async/sync and just directly invoke `block` in current queue (without `dispatch_async`/`dispatch_sync`)
SDCallbackPolicyInvoke = 2,
/// Ensure callback in main thread. Do `dispatch_async` if the `NSThread.isMainTrhead == true` ; else do invoke `block`. Never use `dispatch_sync`, suitable for special UI-related code
SDCallbackPolicySafeAsyncMainThread = 3,
};
/// SDCallbackQueue is a wrapper used to control how the completionBlock should perform on queues, used by our `Cache`/`Manager`/`Loader`.
/// Useful when you call SDWebImage in non-main queue and want to avoid it callback into main queue, which may cause issue.
@interface SDCallbackQueue : NSObject
/// The main queue. This is the default value, has the same effect when passing `nil` to `SDWebImageContextCallbackQueue`
/// The policy defaults to `SDCallbackPolicySafeAsyncMainThread`
@property (nonnull, class, readonly) SDCallbackQueue *mainQueue;
/// The caller current queue. Using `dispatch_get_current_queue`. This is not a dynamic value and only keep the first call time queue.
/// The policy defaults to `SDCallbackPolicySafeExecute`
@property (nonnull, class, readonly) SDCallbackQueue *currentQueue;
/// The global concurrent queue (user-initiated QoS). Using `dispatch_get_global_queue`.
/// The policy defaults to `SDCallbackPolicySafeExecute`
@property (nonnull, class, readonly) SDCallbackQueue *globalQueue;
/// The current queue's callback policy.
@property (nonatomic, assign, readwrite) SDCallbackPolicy policy;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
/// Create the callback queue with a GCD queue. The policy defaults to `SDCallbackPolicySafeExecute`
/// - Parameter queue: The GCD queue, should not be NULL
- (nonnull instancetype)initWithDispatchQueue:(nonnull dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER;
#pragma mark - Execution Entry
/// Submits a block for execution and returns after that block finishes executing.
/// - Parameter block: The block that contains the work to perform.
- (void)sync:(nonnull dispatch_block_t)block API_DEPRECATED("No longer use, may cause deadlock when misused", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0));;
/// Schedules a block asynchronously for execution.
/// - Parameter block: The block that contains the work to perform.
- (void)async:(nonnull dispatch_block_t)block;
@end

View File

@@ -0,0 +1,118 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDCallbackQueue.h"
@interface SDCallbackQueue ()
@property (nonatomic, strong, nonnull) dispatch_queue_t queue;
@end
static inline void SDSafeAsyncMainThread(dispatch_block_t _Nonnull block) {
if (NSThread.isMainThread) {
block();
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
static void SDSafeExecute(dispatch_queue_t queue, dispatch_block_t _Nonnull block, BOOL async) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
dispatch_queue_t currentQueue = dispatch_get_current_queue();
#pragma clang diagnostic pop
if (queue == currentQueue) {
block();
return;
}
// Special handle for main queue only
if (NSThread.isMainThread && queue == dispatch_get_main_queue()) {
block();
return;
}
if (async) {
dispatch_async(queue, block);
} else {
dispatch_sync(queue, block);
}
}
@implementation SDCallbackQueue
- (instancetype)initWithDispatchQueue:(dispatch_queue_t)queue {
self = [super init];
if (self) {
NSCParameterAssert(queue);
_queue = queue;
_policy = SDCallbackPolicySafeExecute;
}
return self;
}
+ (SDCallbackQueue *)mainQueue {
SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_main_queue()];
queue->_policy = SDCallbackPolicySafeAsyncMainThread;
return queue;
}
+ (SDCallbackQueue *)currentQueue {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_current_queue()];
#pragma clang diagnostic pop
return queue;
}
+ (SDCallbackQueue *)globalQueue {
SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];
return queue;
}
- (void)sync:(nonnull dispatch_block_t)block {
switch (self.policy) {
case SDCallbackPolicySafeExecute:
SDSafeExecute(self.queue, block, NO);
break;
case SDCallbackPolicyDispatch:
dispatch_sync(self.queue, block);
break;
case SDCallbackPolicyInvoke:
block();
break;
case SDCallbackPolicySafeAsyncMainThread:
SDSafeAsyncMainThread(block);
break;
default:
NSCAssert(NO, @"unexpected policy %tu", self.policy);
break;
}
}
- (void)async:(nonnull dispatch_block_t)block {
switch (self.policy) {
case SDCallbackPolicySafeExecute:
SDSafeExecute(self.queue, block, YES);
break;
case SDCallbackPolicyDispatch:
dispatch_async(self.queue, block);
break;
case SDCallbackPolicyInvoke:
block();
break;
case SDCallbackPolicySafeAsyncMainThread:
SDSafeAsyncMainThread(block);
break;
default:
NSCAssert(NO, @"unexpected policy %tu", self.policy);
break;
}
}
@end

View File

@@ -0,0 +1,146 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
@class SDImageCacheConfig;
/**
A protocol to allow custom disk cache used in SDImageCache.
*/
@protocol SDDiskCache <NSObject>
// All of these method are called from the same global queue to avoid blocking on main queue and thread-safe problem. But it's also recommend to ensure thread-safe yourself using lock or other ways.
@required
/**
Create a new disk cache based on the specified path. You can check `maxDiskSize` and `maxDiskAge` used for disk cache.
@param cachePath Full path of a directory in which the cache will write data.
Once initialized you should not read and write to this directory.
@param config The cache config to be used to create the cache.
@return A new cache object, or nil if an error occurs.
*/
- (nullable instancetype)initWithCachePath:(nonnull NSString *)cachePath config:(nonnull SDImageCacheConfig *)config;
/**
Returns a boolean value that indicates whether a given key is in cache.
This method may blocks the calling thread until file read finished.
@param key A string identifying the data. If nil, just return NO.
@return Whether the key is in cache.
*/
- (BOOL)containsDataForKey:(nonnull NSString *)key;
/**
Returns the data associated with a given key.
This method may blocks the calling thread until file read finished.
@param key A string identifying the data. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable NSData *)dataForKey:(nonnull NSString *)key;
/**
Sets the value of the specified key in the cache.
This method may blocks the calling thread until file write finished.
@param data The data to be stored in the cache.
@param key The key with which to associate the value. If nil, this method has no effect.
*/
- (void)setData:(nullable NSData *)data forKey:(nonnull NSString *)key;
/**
Returns the extended data associated with a given key.
This method may blocks the calling thread until file read finished.
@param key A string identifying the data. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable NSData *)extendedDataForKey:(nonnull NSString *)key;
/**
Set extended data with a given key.
@discussion You can set any extended data to exist cache key. Without override the exist disk file data.
on UNIX, the common way for this is to use the Extended file attributes (xattr)
@param extendedData The extended data (pass nil to remove).
@param key The key with which to associate the value. If nil, this method has no effect.
*/
- (void)setExtendedData:(nullable NSData *)extendedData forKey:(nonnull NSString *)key;
/**
Removes the value of the specified key in the cache.
This method may blocks the calling thread until file delete finished.
@param key The key identifying the value to be removed. If nil, this method has no effect.
*/
- (void)removeDataForKey:(nonnull NSString *)key;
/**
Empties the cache.
This method may blocks the calling thread until file delete finished.
*/
- (void)removeAllData;
/**
Removes the expired data from the cache. You can choose the data to remove base on `ageLimit`, `countLimit` and `sizeLimit` options.
*/
- (void)removeExpiredData;
/**
The cache path for key
@param key A string identifying the value
@return The cache path for key. Or nil if the key can not associate to a path
*/
- (nullable NSString *)cachePathForKey:(nonnull NSString *)key;
/**
Returns the number of data in this cache.
This method may blocks the calling thread until file read finished.
@return The total data count.
*/
- (NSUInteger)totalCount;
/**
Returns the total size (in bytes) of data in this cache.
This method may blocks the calling thread until file read finished.
@return The total data size in bytes.
*/
- (NSUInteger)totalSize;
@end
/**
The built-in disk cache.
*/
@interface SDDiskCache : NSObject <SDDiskCache>
/**
Cache Config object - storing all kind of settings.
*/
@property (nonatomic, strong, readonly, nonnull) SDImageCacheConfig *config;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
/**
Move the cache directory from old location to new location, the old location will be removed after finish.
If the old location does not exist, does nothing.
If the new location does not exist, only do a movement of directory.
If the new location does exist, will move and merge the files from old location.
If the new location does exist, but is not a directory, will remove it and do a movement of directory.
@param srcPath old location of cache directory
@param dstPath new location of cache directory
*/
- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath;
@end

View File

@@ -0,0 +1,390 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDDiskCache.h"
#import "SDImageCacheConfig.h"
#import "SDFileAttributeHelper.h"
#import <CommonCrypto/CommonDigest.h>
static NSString * const SDDiskCacheExtendedAttributeName = @"com.hackemist.SDDiskCache";
@interface SDDiskCache ()
@property (nonatomic, copy) NSString *diskCachePath;
@property (nonatomic, strong, nonnull) NSFileManager *fileManager;
@end
@implementation SDDiskCache
- (instancetype)init {
NSAssert(NO, @"Use `initWithCachePath:` with the disk cache path");
return nil;
}
#pragma mark - SDcachePathForKeyDiskCache Protocol
- (instancetype)initWithCachePath:(NSString *)cachePath config:(nonnull SDImageCacheConfig *)config {
if (self = [super init]) {
_diskCachePath = cachePath;
_config = config;
[self commonInit];
}
return self;
}
- (void)commonInit {
if (self.config.fileManager) {
self.fileManager = self.config.fileManager;
} else {
self.fileManager = [NSFileManager new];
}
[self createDirectory];
}
- (BOOL)containsDataForKey:(NSString *)key {
NSParameterAssert(key);
NSString *filePath = [self cachePathForKey:key];
BOOL exists = [self.fileManager fileExistsAtPath:filePath];
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// checking the key with and without the extension
if (!exists) {
exists = [self.fileManager fileExistsAtPath:filePath.stringByDeletingPathExtension];
}
return exists;
}
- (NSData *)dataForKey:(NSString *)key {
NSParameterAssert(key);
NSString *filePath = [self cachePathForKey:key];
// if filePath is nil or (null)framework will crash with this
// Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_NSPlaceholderData initWithContentsOfFile:options:maxLength:error:]: nil file argument'
if (filePath == nil || [@"(null)" isEqualToString: filePath]) {
return nil;
}
NSData *data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
if (data) {
[[NSURL fileURLWithPath:filePath] setResourceValue:[NSDate date] forKey:NSURLContentAccessDateKey error:nil];
return data;
}
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// checking the key with and without the extension
filePath = filePath.stringByDeletingPathExtension;
data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
if (data) {
[[NSURL fileURLWithPath:filePath] setResourceValue:[NSDate date] forKey:NSURLContentAccessDateKey error:nil];
return data;
}
return nil;
}
- (void)setData:(NSData *)data forKey:(NSString *)key {
NSParameterAssert(data);
NSParameterAssert(key);
// get cache Path for image key
NSString *cachePathForKey = [self cachePathForKey:key];
// transform to NSURL
NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey isDirectory:NO];
[data writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil];
}
- (NSData *)extendedDataForKey:(NSString *)key {
NSParameterAssert(key);
// get cache Path for image key
NSString *cachePathForKey = [self cachePathForKey:key];
NSData *extendedData = [SDFileAttributeHelper extendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil];
return extendedData;
}
- (void)setExtendedData:(NSData *)extendedData forKey:(NSString *)key {
NSParameterAssert(key);
// get cache Path for image key
NSString *cachePathForKey = [self cachePathForKey:key];
if (!extendedData) {
// Remove
[SDFileAttributeHelper removeExtendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil];
} else {
// Override
[SDFileAttributeHelper setExtendedAttribute:SDDiskCacheExtendedAttributeName value:extendedData atPath:cachePathForKey traverseLink:NO overwrite:YES error:nil];
}
}
- (void)removeDataForKey:(NSString *)key {
NSParameterAssert(key);
NSString *filePath = [self cachePathForKey:key];
[self.fileManager removeItemAtPath:filePath error:nil];
}
- (void)removeAllData {
[self.fileManager removeItemAtPath:self.diskCachePath error:nil];
[self createDirectory];
}
- (void)createDirectory {
[self.fileManager createDirectoryAtPath:self.diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
// disable iCloud backup
if (self.config.shouldDisableiCloud) {
// ignore iCloud backup resource value error
[[NSURL fileURLWithPath:self.diskCachePath isDirectory:YES] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}
- (void)removeExpiredData {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
// Compute content date key to be used for tests
NSURLResourceKey cacheContentDateKey;
switch (self.config.diskCacheExpireType) {
case SDImageCacheConfigExpireTypeModificationDate:
cacheContentDateKey = NSURLContentModificationDateKey;
break;
case SDImageCacheConfigExpireTypeCreationDate:
cacheContentDateKey = NSURLCreationDateKey;
break;
case SDImageCacheConfigExpireTypeChangeDate:
cacheContentDateKey = NSURLAttributeModificationDateKey;
break;
case SDImageCacheConfigExpireTypeAccessDate:
default:
cacheContentDateKey = NSURLContentAccessDateKey;
break;
}
NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey];
// This enumerator prefetches useful properties for our cache files.
NSDirectoryEnumerator<NSURL *> *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:resourceKeys
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
NSDate *expirationDate = (self.config.maxDiskAge < 0) ? nil: [NSDate dateWithTimeIntervalSinceNow:-self.config.maxDiskAge];
NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *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.
NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
for (NSURL *fileURL in fileEnumerator) {
@autoreleasepool {
NSError *error;
NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
// Skip directories and errors.
if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
continue;
}
// Remove files that are older than the expiration date;
NSDate *modifiedDate = resourceValues[cacheContentDateKey];
if (expirationDate && [[modifiedDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
[urlsToDelete addObject:fileURL];
continue;
}
// Store a reference to this file and account for its total size.
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
cacheFiles[fileURL] = resourceValues;
}
}
for (NSURL *fileURL in urlsToDelete) {
[self.fileManager removeItemAtURL:fileURL error:nil];
}
// If our remaining disk cache exceeds a configured maximum size, perform a second
// size-based cleanup pass. We delete the oldest files first.
NSUInteger maxDiskSize = self.config.maxDiskSize;
if (maxDiskSize > 0 && currentCacheSize > maxDiskSize) {
// Target half of our maximum cache size for this cleanup pass.
const NSUInteger desiredCacheSize = maxDiskSize / 2;
// Sort the remaining cache files by their last modification time or last access time (oldest first).
NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
usingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1[cacheContentDateKey] compare:obj2[cacheContentDateKey]];
}];
// Delete files until we fall below our desired cache size.
for (NSURL *fileURL in sortedFiles) {
if ([self.fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
if (currentCacheSize < desiredCacheSize) {
break;
}
}
}
}
}
- (nullable NSString *)cachePathForKey:(NSString *)key {
NSParameterAssert(key);
return [self cachePathForKey:key inPath:self.diskCachePath];
}
- (NSUInteger)totalSize {
NSUInteger size = 0;
// Use URL-based enumerator instead of Path(NSString *)-based enumerator to reduce
// those objects(ex. NSPathStore2/_NSCFString/NSConcreteData) created during traversal.
// Even worse, those objects are added into AutoreleasePool, in background threads,
// the time to release those objects is undifined(according to the usage of CPU)
// It will truely consumes a lot of VM, up to cause OOMs.
@autoreleasepool {
NSURL *pathURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
NSDirectoryEnumerator<NSURL *> *fileEnumerator = [self.fileManager enumeratorAtURL:pathURL
includingPropertiesForKeys:@[NSURLFileSizeKey]
options:(NSDirectoryEnumerationOptions)0
errorHandler:NULL];
for (NSURL *fileURL in fileEnumerator) {
@autoreleasepool {
NSNumber *fileSize;
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
size += fileSize.unsignedIntegerValue;
}
}
}
return size;
}
- (NSUInteger)totalCount {
NSUInteger count = 0;
@autoreleasepool {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
NSDirectoryEnumerator<NSURL *> *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:@[] options:(NSDirectoryEnumerationOptions)0 errorHandler:nil];
count = fileEnumerator.allObjects.count;
}
return count;
}
#pragma mark - Cache paths
- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
NSString *filename = SDDiskCacheFileNameForKey(key);
return [path stringByAppendingPathComponent:filename];
}
- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath {
NSParameterAssert(srcPath);
NSParameterAssert(dstPath);
// Check if old path is equal to new path
if ([srcPath isEqualToString:dstPath]) {
return;
}
BOOL isDirectory;
// Check if old path is directory
if (![self.fileManager fileExistsAtPath:srcPath isDirectory:&isDirectory] || !isDirectory) {
return;
}
// Check if new path is directory
if (![self.fileManager fileExistsAtPath:dstPath isDirectory:&isDirectory] || !isDirectory) {
if (!isDirectory) {
// New path is not directory, remove file
[self.fileManager removeItemAtPath:dstPath error:nil];
}
NSString *dstParentPath = [dstPath stringByDeletingLastPathComponent];
// Creates any non-existent parent directories as part of creating the directory in path
if (![self.fileManager fileExistsAtPath:dstParentPath]) {
[self.fileManager createDirectoryAtPath:dstParentPath withIntermediateDirectories:YES attributes:nil error:NULL];
}
// New directory does not exist, rename directory
[self.fileManager moveItemAtPath:srcPath toPath:dstPath error:nil];
// disable iCloud backup
if (self.config.shouldDisableiCloud) {
// ignore iCloud backup resource value error
[[NSURL fileURLWithPath:dstPath isDirectory:YES] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
}
} else {
// New directory exist, merge the files
NSURL *srcURL = [NSURL fileURLWithPath:srcPath isDirectory:YES];
NSDirectoryEnumerator<NSURL *> *srcDirEnumerator = [self.fileManager enumeratorAtURL:srcURL
includingPropertiesForKeys:@[]
options:(NSDirectoryEnumerationOptions)0
errorHandler:NULL];
for (NSURL *url in srcDirEnumerator) {
@autoreleasepool {
NSString *dstFilePath = [dstPath stringByAppendingPathComponent:url.lastPathComponent];
NSURL *dstFileURL = [NSURL fileURLWithPath:dstFilePath isDirectory:NO];
[self.fileManager moveItemAtURL:url toURL:dstFileURL error:nil];
}
}
// Remove the old path
[self.fileManager removeItemAtURL:srcURL error:nil];
}
}
#pragma mark - Hash
static inline NSString *SDSanitizeFileNameString(NSString * _Nullable fileName) {
if ([fileName length] == 0) {
return fileName;
}
// note: `:` is the only invalid char on Apple file system
// but `/` or `\` is valid
// \0 is also special case (which cause Foundation API treat the C string as EOF)
NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"\0:"];
return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""];
}
#define SD_MAX_FILE_EXTENSION_LENGTH (NAME_MAX - CC_MD5_DIGEST_LENGTH * 2 - 1)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
static inline NSString * _Nonnull SDDiskCacheFileNameForKey(NSString * _Nullable 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 *ext;
// 1. Use URL path extname if valid
NSURL *keyURL = [NSURL URLWithString:key];
if (keyURL) {
ext = keyURL.pathExtension;
}
// 2. Use file extname if valid
if (!ext) {
ext = key.pathExtension;
}
// 3. Check if extname valid on file system
ext = SDSanitizeFileNameString(ext);
// File system has file name length limit, we need to check if ext is too long, we don't add it to the filename
if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) {
ext = nil;
}
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], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]];
return filename;
}
#pragma clang diagnostic pop
@end

View File

@@ -0,0 +1,84 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
/**
These following class are provided to use `UIGraphicsImageRenderer` with polyfill, which allows write cross-platform(AppKit/UIKit) code and avoid runtime version check.
Compared to `UIGraphicsBeginImageContext`, `UIGraphicsImageRenderer` use dynamic bitmap from your draw code to generate CGContext, not always use ARGB8888, which is more performant on RAM usage.
Which means, if you draw CGImage/CIImage which contains grayscale only, the underlaying bitmap context use grayscale, it's managed by system and not a fixed type. (actually, the `kCGContextTypeAutomatic`)
For usage, See more in Apple's documentation: https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer
For UIKit on iOS/tvOS 10+, these method just use the same `UIGraphicsImageRenderer` API.
For others (macOS/watchOS or iOS/tvOS 10-), these method use the `SDImageGraphics.h` to implements the same behavior (but without dynamic bitmap support)
*/
/// A closure for drawing an image.
typedef void (^SDGraphicsImageDrawingActions)(CGContextRef _Nonnull context);
/// Constants that specify the color range of the image renderer context.
typedef NS_ENUM(NSInteger, SDGraphicsImageRendererFormatRange) {
/// The image renderer context doesnt specify a color range.
SDGraphicsImageRendererFormatRangeUnspecified = -1,
/// The system automatically chooses the image renderer contexts pixel format according to the color range of its content.
SDGraphicsImageRendererFormatRangeAutomatic = 0,
/// The image renderer context supports wide color.
SDGraphicsImageRendererFormatRangeExtended,
/// The image renderer context doesnt support extended colors.
SDGraphicsImageRendererFormatRangeStandard
};
/// A set of drawing attributes that represent the configuration of an image renderer context.
@interface SDGraphicsImageRendererFormat : NSObject
#if SD_UIKIT
/// The underlying uiformat for UIKit. This usage of this API should be careful, which may cause out of sync.
@property (nonatomic, strong, nonnull) UIGraphicsImageRendererFormat *uiformat API_AVAILABLE(ios(10.0), tvos(10.0));
#endif
/// The display scale of the image renderer context.
/// The default value is equal to the scale of the main screen.
@property (nonatomic) CGFloat scale;
/// A Boolean value indicating whether the underlying Core Graphics context has an alpha channel.
/// The default value is NO.
@property (nonatomic) BOOL opaque;
/// Specifying whether the bitmap context should use extended color.
/// For iOS 12+, the value is from system `preferredRange` property
/// For iOS 10-11, the value is from system `prefersExtendedRange` property
/// For iOS 9-, the value is `.standard`
@property (nonatomic) SDGraphicsImageRendererFormatRange preferredRange;
/// Init the default format. See each properties's default value.
- (nonnull instancetype)init;
/// Returns a new format best suited for the main screens current configuration.
+ (nonnull instancetype)preferredFormat;
@end
/// A graphics renderer for creating Core Graphics-backed images.
@interface SDGraphicsImageRenderer : NSObject
/// Creates an image renderer for drawing images of a given size.
/// @param size The size of images output from the renderer, specified in points.
/// @return An initialized image renderer.
- (nonnull instancetype)initWithSize:(CGSize)size;
/// Creates a new image renderer with a given size and format.
/// @param size The size of images output from the renderer, specified in points.
/// @param format A SDGraphicsImageRendererFormat object that encapsulates the format used to create the renderer context.
/// @return An initialized image renderer.
- (nonnull instancetype)initWithSize:(CGSize)size format:(nonnull SDGraphicsImageRendererFormat *)format;
/// Creates an image by following a set of drawing instructions.
/// @param actions A SDGraphicsImageDrawingActions block that, when invoked by the renderer, executes a set of drawing instructions to create the output image.
/// @note You should not retain or use the context outside the block, it's non-escaping.
/// @return A UIImage object created by the supplied drawing actions.
- (nonnull UIImage *)imageWithActions:(nonnull NS_NOESCAPE SDGraphicsImageDrawingActions)actions;
@end

View File

@@ -0,0 +1,229 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDGraphicsImageRenderer.h"
#import "SDImageGraphics.h"
#import "SDDeviceHelper.h"
@implementation SDGraphicsImageRendererFormat
@synthesize scale = _scale;
@synthesize opaque = _opaque;
@synthesize preferredRange = _preferredRange;
#pragma mark - Property
- (CGFloat)scale {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
return self.uiformat.scale;
} else {
return _scale;
}
#else
return _scale;
#endif
}
- (void)setScale:(CGFloat)scale {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
self.uiformat.scale = scale;
} else {
_scale = scale;
}
#else
_scale = scale;
#endif
}
- (BOOL)opaque {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
return self.uiformat.opaque;
} else {
return _opaque;
}
#else
return _opaque;
#endif
}
- (void)setOpaque:(BOOL)opaque {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
self.uiformat.opaque = opaque;
} else {
_opaque = opaque;
}
#else
_opaque = opaque;
#endif
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (SDGraphicsImageRendererFormatRange)preferredRange {
#if SD_VISION
return (SDGraphicsImageRendererFormatRange)self.uiformat.preferredRange;
#elif SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
if (@available(iOS 12.0, tvOS 12.0, *)) {
return (SDGraphicsImageRendererFormatRange)self.uiformat.preferredRange;
} else {
BOOL prefersExtendedRange = self.uiformat.prefersExtendedRange;
if (prefersExtendedRange) {
return SDGraphicsImageRendererFormatRangeExtended;
} else {
return SDGraphicsImageRendererFormatRangeStandard;
}
}
} else {
return _preferredRange;
}
#else
return _preferredRange;
#endif
}
- (void)setPreferredRange:(SDGraphicsImageRendererFormatRange)preferredRange {
#if SD_VISION
self.uiformat.preferredRange = (UIGraphicsImageRendererFormatRange)preferredRange;
#elif SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
if (@available(iOS 12.0, tvOS 12.0, *)) {
self.uiformat.preferredRange = (UIGraphicsImageRendererFormatRange)preferredRange;
} else {
switch (preferredRange) {
case SDGraphicsImageRendererFormatRangeExtended:
self.uiformat.prefersExtendedRange = YES;
break;
case SDGraphicsImageRendererFormatRangeStandard:
self.uiformat.prefersExtendedRange = NO;
default:
// Automatic means default
break;
}
}
} else {
_preferredRange = preferredRange;
}
#else
_preferredRange = preferredRange;
#endif
}
#pragma clang diagnostic pop
- (instancetype)init {
self = [super init];
if (self) {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.10, *)) {
UIGraphicsImageRendererFormat *uiformat = [[UIGraphicsImageRendererFormat alloc] init];
self.uiformat = uiformat;
} else {
#endif
CGFloat screenScale = SDDeviceHelper.screenScale;
self.scale = screenScale;
self.opaque = NO;
#if SD_UIKIT
}
#endif
}
return self;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
- (instancetype)initForMainScreen {
self = [super init];
if (self) {
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.0, *)) {
UIGraphicsImageRendererFormat *uiformat;
// iOS 11.0.0 GM does have `preferredFormat`, but iOS 11 betas did not (argh!)
if ([UIGraphicsImageRenderer respondsToSelector:@selector(preferredFormat)]) {
uiformat = [UIGraphicsImageRendererFormat preferredFormat];
} else {
uiformat = [UIGraphicsImageRendererFormat defaultFormat];
}
self.uiformat = uiformat;
} else {
#endif
CGFloat screenScale = SDDeviceHelper.screenScale;
self.scale = screenScale;
self.opaque = NO;
#if SD_UIKIT
}
#endif
}
return self;
}
#pragma clang diagnostic pop
+ (instancetype)preferredFormat {
SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] initForMainScreen];
return format;
}
@end
@interface SDGraphicsImageRenderer ()
@property (nonatomic, assign) CGSize size;
@property (nonatomic, strong) SDGraphicsImageRendererFormat *format;
#if SD_UIKIT
@property (nonatomic, strong) UIGraphicsImageRenderer *uirenderer API_AVAILABLE(ios(10.0), tvos(10.0));
#endif
@end
@implementation SDGraphicsImageRenderer
- (instancetype)initWithSize:(CGSize)size {
return [self initWithSize:size format:SDGraphicsImageRendererFormat.preferredFormat];
}
- (instancetype)initWithSize:(CGSize)size format:(SDGraphicsImageRendererFormat *)format {
NSParameterAssert(format);
self = [super init];
if (self) {
self.size = size;
self.format = format;
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.0, *)) {
UIGraphicsImageRendererFormat *uiformat = format.uiformat;
self.uirenderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:uiformat];
}
#endif
}
return self;
}
- (UIImage *)imageWithActions:(NS_NOESCAPE SDGraphicsImageDrawingActions)actions {
NSParameterAssert(actions);
#if SD_UIKIT
if (@available(iOS 10.0, tvOS 10.0, *)) {
UIGraphicsImageDrawingActions uiactions = ^(UIGraphicsImageRendererContext *rendererContext) {
if (actions) {
actions(rendererContext.CGContext);
}
};
return [self.uirenderer imageWithActions:uiactions];
} else {
#endif
SDGraphicsBeginImageContextWithOptions(self.size, self.format.opaque, self.format.scale);
CGContextRef context = SDGraphicsGetCurrentContext();
if (actions) {
actions(context);
}
UIImage *image = SDGraphicsGetImageFromCurrentImageContext();
SDGraphicsEndImageContext();
return image;
#if SD_UIKIT
}
#endif
}
@end

View File

@@ -0,0 +1,19 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageIOAnimatedCoder.h"
/**
Built in coder using ImageIO that supports APNG encoding/decoding
*/
@interface SDImageAPNGCoder : SDImageIOAnimatedCoder <SDProgressiveImageCoder, SDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) SDImageAPNGCoder *sharedCoder;
@end

View File

@@ -0,0 +1,58 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageAPNGCoder.h"
#import "SDImageIOAnimatedCoderInternal.h"
#if SD_MAC
#import <CoreServices/CoreServices.h>
#else
#import <MobileCoreServices/MobileCoreServices.h>
#endif
@implementation SDImageAPNGCoder
+ (instancetype)sharedCoder {
static SDImageAPNGCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageAPNGCoder alloc] init];
});
return coder;
}
#pragma mark - Subclass Override
+ (SDImageFormat)imageFormat {
return SDImageFormatPNG;
}
+ (NSString *)imageUTType {
return (__bridge NSString *)kSDUTTypePNG;
}
+ (NSString *)dictionaryProperty {
return (__bridge NSString *)kCGImagePropertyPNGDictionary;
}
+ (NSString *)unclampedDelayTimeProperty {
return (__bridge NSString *)kCGImagePropertyAPNGUnclampedDelayTime;
}
+ (NSString *)delayTimeProperty {
return (__bridge NSString *)kCGImagePropertyAPNGDelayTime;
}
+ (NSString *)loopCountProperty {
return (__bridge NSString *)kCGImagePropertyAPNGLoopCount;
}
+ (NSUInteger)defaultLoopCount {
return 0;
}
@end

View File

@@ -0,0 +1,23 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageIOAnimatedCoder.h"
/**
This coder is used for Google WebP and Animated WebP(AWebP) image format.
Image/IO provide the WebP decoding support in iOS 14/macOS 11/tvOS 14/watchOS 7+.
@note Currently Image/IO seems does not supports WebP encoding, if you need WebP encoding, use the custom codec below.
@note If you need to support lower firmware version for WebP, you can have a try at https://github.com/SDWebImage/SDWebImageWebPCoder
*/
API_AVAILABLE(ios(14.0), tvos(14.0), macos(11.0), watchos(7.0))
@interface SDImageAWebPCoder : SDImageIOAnimatedCoder <SDProgressiveImageCoder, SDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) SDImageAWebPCoder *sharedCoder;
@end

View File

@@ -0,0 +1,98 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageAWebPCoder.h"
#import "SDImageIOAnimatedCoderInternal.h"
// These constants are available from iOS 14+ and Xcode 12. This raw value is used for toolchain and firmware compatibility
static NSString * kSDCGImagePropertyWebPDictionary = @"{WebP}";
static NSString * kSDCGImagePropertyWebPLoopCount = @"LoopCount";
static NSString * kSDCGImagePropertyWebPDelayTime = @"DelayTime";
static NSString * kSDCGImagePropertyWebPUnclampedDelayTime = @"UnclampedDelayTime";
@implementation SDImageAWebPCoder
+ (void)initialize {
#if __IPHONE_14_0 || __TVOS_14_0 || __MAC_11_0 || __WATCHOS_7_0
// Xcode 12
if (@available(iOS 14, tvOS 14, macOS 11, watchOS 7, *)) {
// Use SDK instead of raw value
kSDCGImagePropertyWebPDictionary = (__bridge NSString *)kCGImagePropertyWebPDictionary;
kSDCGImagePropertyWebPLoopCount = (__bridge NSString *)kCGImagePropertyWebPLoopCount;
kSDCGImagePropertyWebPDelayTime = (__bridge NSString *)kCGImagePropertyWebPDelayTime;
kSDCGImagePropertyWebPUnclampedDelayTime = (__bridge NSString *)kCGImagePropertyWebPUnclampedDelayTime;
}
#endif
}
+ (instancetype)sharedCoder {
static SDImageAWebPCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageAWebPCoder alloc] init];
});
return coder;
}
#pragma mark - SDImageCoder
- (BOOL)canDecodeFromData:(nullable NSData *)data {
switch ([NSData sd_imageFormatForImageData:data]) {
case SDImageFormatWebP:
// Check WebP decoding compatibility
return [self.class canDecodeFromFormat:SDImageFormatWebP];
default:
return NO;
}
}
- (BOOL)canIncrementalDecodeFromData:(NSData *)data {
return [self canDecodeFromData:data];
}
- (BOOL)canEncodeToFormat:(SDImageFormat)format {
switch (format) {
case SDImageFormatWebP:
// Check WebP encoding compatibility
return [self.class canEncodeToFormat:SDImageFormatWebP];
default:
return NO;
}
}
#pragma mark - Subclass Override
+ (SDImageFormat)imageFormat {
return SDImageFormatWebP;
}
+ (NSString *)imageUTType {
return (__bridge NSString *)kSDUTTypeWebP;
}
+ (NSString *)dictionaryProperty {
return kSDCGImagePropertyWebPDictionary;
}
+ (NSString *)unclampedDelayTimeProperty {
return kSDCGImagePropertyWebPUnclampedDelayTime;
}
+ (NSString *)delayTimeProperty {
return kSDCGImagePropertyWebPDelayTime;
}
+ (NSString *)loopCountProperty {
return kSDCGImagePropertyWebPLoopCount;
}
+ (NSUInteger)defaultLoopCount {
return 0;
}
@end

View File

@@ -0,0 +1,477 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDWebImageDefine.h"
#import "SDImageCacheConfig.h"
#import "SDImageCacheDefine.h"
#import "SDMemoryCache.h"
#import "SDDiskCache.h"
/// Image Cache Options
typedef NS_OPTIONS(NSUInteger, SDImageCacheOptions) {
/**
* By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDImageCacheQueryMemoryDataSync`
*/
SDImageCacheQueryMemoryData = 1 << 0,
/**
* By default, when you only specify `SDImageCacheQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously.
*/
SDImageCacheQueryMemoryDataSync = 1 << 1,
/**
* By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously.
@note These 3 query options can be combined together. For the full list about these masks combination, see wiki page.
*/
SDImageCacheQueryDiskDataSync = 1 << 2,
/**
* By default, images are decoded respecting their original size. On iOS, this flag will scale down the
* images to a size compatible with the constrained memory of devices.
*/
SDImageCacheScaleDownLargeImages = 1 << 3,
/**
* By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation.
* However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image.
* @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not)
* @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option
*/
SDImageCacheAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 4,
/**
* By default, we decode the animated image. This flag can force decode the first frame only and produce the static image.
*/
SDImageCacheDecodeFirstFrameOnly = 1 << 5,
/**
* By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from disk cache
*/
SDImageCachePreloadAllFrames = 1 << 6,
/**
* By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution.
* Using this option, can ensure we always produce image with your provided class. If failed, an error with code `SDWebImageErrorBadImageData` will be used.
* Note this options is not compatible with `SDImageCacheDecodeFirstFrameOnly`, which always produce a UIImage/NSImage.
*/
SDImageCacheMatchAnimatedImageClass = 1 << 7,
};
/**
* A token associated with each cache query. Can be used to cancel a cache query
*/
@interface SDImageCacheToken : NSObject <SDWebImageOperation>
/**
Cancel the current cache query.
*/
- (void)cancel;
/**
The query's cache key.
*/
@property (nonatomic, strong, nullable, readonly) NSString *key;
@end
/**
* SDImageCache maintains a memory cache and a disk cache. Disk cache write operations are performed
* asynchronous so it doesnt add unnecessary latency to the UI.
*/
@interface SDImageCache : NSObject
#pragma mark - Properties
/**
* Cache Config object - storing all kind of settings.
* The property is copy so change of current config will not accidentally affect other cache's config.
*/
@property (nonatomic, copy, nonnull, readonly) SDImageCacheConfig *config;
/**
* The memory cache implementation object used for current image cache.
* By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method.
* @note To customize this class, check `SDImageCacheConfig.memoryCacheClass` property.
*/
@property (nonatomic, strong, readonly, nonnull) id<SDMemoryCache> memoryCache;
/**
* The disk cache implementation object used for current image cache.
* By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method.
* @note To customize this class, check `SDImageCacheConfig.diskCacheClass` property.
* @warning When calling method about read/write in disk cache, be sure to either make your disk cache implementation IO-safe or using the same access queue to avoid issues.
*/
@property (nonatomic, strong, readonly, nonnull) id<SDDiskCache> diskCache;
/**
* The disk cache's root path
*/
@property (nonatomic, copy, nonnull, readonly) NSString *diskCachePath;
/**
* The additional disk cache path to check if the query from disk cache not exist;
* The `key` param is the image cache key. The returned file path will be used to load the disk cache. If return nil, ignore it.
* Useful if you want to bundle pre-loaded images with your app
*/
@property (nonatomic, copy, nullable) SDImageCacheAdditionalCachePathBlock additionalCachePathBlock;
#pragma mark - Singleton and initialization
/**
* Returns global shared cache instance
*/
@property (nonatomic, class, readonly, nonnull) SDImageCache *sharedImageCache;
/**
* Control the default disk cache directory. This will effect all the SDImageCache instance created after modification, even for shared image cache.
* This can be used to share the same disk cache with the App and App Extension (Today/Notification Widget) using `- [NSFileManager.containerURLForSecurityApplicationGroupIdentifier:]`.
* @note If you pass nil, the value will be reset to `~/Library/Caches/com.hackemist.SDImageCache`.
* @note We still preserve the `namespace` arg, which means, if you change this property into `/path/to/use`, the `SDImageCache.sharedImageCache.diskCachePath` should be `/path/to/use/default` because shared image cache use `default` as namespace.
* Defaults to nil.
*/
@property (nonatomic, class, readwrite, null_resettable) NSString *defaultDiskCacheDirectory;
/**
* Init a new cache store with a specific namespace
* The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/)
*
* @param ns The namespace to use for this cache store
*/
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns;
/**
* Init a new cache store with a specific namespace and directory.
* The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/)
*
* @param ns The namespace to use for this cache store
* @param directory Directory to cache disk images in
*/
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
diskCacheDirectory:(nullable NSString *)directory;
/**
* Init a new cache store with a specific namespace, directory and config.
* The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/)
*
* @param ns The namespace to use for this cache store
* @param directory Directory to cache disk images in
* @param config The cache config to be used to create the cache. You can provide custom memory cache or disk cache class in the cache config
*/
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
diskCacheDirectory:(nullable NSString *)directory
config:(nullable SDImageCacheConfig *)config NS_DESIGNATED_INITIALIZER;
#pragma mark - Cache paths
/**
Get the cache path for a certain key
@param key The unique image cache key
@return The cache path. You can check `lastPathComponent` to grab the file name.
*/
- (nullable NSString *)cachePathForKey:(nullable NSString *)key;
#pragma mark - Store Ops
/**
* Asynchronously 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
* @param completionBlock A block executed after the operation is finished
*/
- (void)storeImage:(nullable UIImage *)image
forKey:(nullable NSString *)key
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
/**
* Asynchronously 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
* @param toDisk Store the image to disk cache if YES. If NO, the completion block is called synchronously
* @param completionBlock A block executed after the operation is finished
* @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG.
*/
- (void)storeImage:(nullable UIImage *)image
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
/**
* Asynchronously store an image data into disk cache at the given key.
*
* @param imageData The image data to store
* @param key The unique image cache key, usually it's image absolute URL
* @param completionBlock A block executed after the operation is finished
*/
- (void)storeImageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
/**
* Asynchronously store an image into memory and disk cache at the given key.
*
* @param image The image to store
* @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. If NO, the completion block is called synchronously
* @param completionBlock A block executed after the operation is finished
* @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG.
*/
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
/**
* Asynchronously store an image into memory and disk cache at the given key.
*
* @param image The image to store
* @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 options A mask to specify options to use for this store
* @param context The context options to use. Pass `.callbackQueue` to control callback queue
* @param cacheType The image store op cache type
* @param completionBlock A block executed after the operation is finished
* @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG.
*/
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
/**
* Synchronously store an image into memory 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)storeImageToMemory:(nullable UIImage*)image
forKey:(nullable NSString *)key;
/**
* Synchronously store an image data into disk cache at the given key.
*
* @param imageData The image data to store
* @param key The unique image cache key, usually it's image absolute URL
*/
- (void)storeImageDataToDisk:(nullable NSData *)imageData
forKey:(nullable NSString *)key;
#pragma mark - Contains and Check Ops
/**
* Asynchronously check if image exists in disk cache already (does not load the image)
*
* @param key the key describing the url
* @param completionBlock the block to be executed when the check is done.
* @note the completion block will be always executed on the main queue
*/
- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDImageCacheCheckCompletionBlock)completionBlock;
/**
* Synchronously check if image data exists in disk cache already (does not load the image)
*
* @param key the key describing the url
*/
- (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key;
#pragma mark - Query and Retrieve Ops
/**
* Synchronously query the image data for the given key in disk cache. You can decode the image data to image after loaded.
*
* @param key The unique key used to store the wanted image
* @return The image data for the given key, or nil if not found.
*/
- (nullable NSData *)diskImageDataForKey:(nullable NSString *)key;
/**
* Asynchronously query the image data for the given key in disk cache. You can decode the image data to image after loaded.
*
* @param key The unique key used to store the wanted image
* @param completionBlock the block to be executed when the query is done.
* @note the completion block will be always executed on the main queue
*/
- (void)diskImageDataQueryForKey:(nullable NSString *)key completion:(nullable SDImageCacheQueryDataCompletionBlock)completionBlock;
/**
* Asynchronously queries the cache with operation and call the completion when done.
*
* @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`.
* @param doneBlock The completion block. Will not get called if the operation is cancelled
*
* @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled
*/
- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDImageCacheQueryCompletionBlock)doneBlock;
/**
* Asynchronously queries the cache with operation and call the completion when done.
*
* @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`.
* @param options A mask to specify options to use for this cache query
* @param doneBlock The completion block. Will not get called if the operation is cancelled
*
* @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled
* @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior.
*/
- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDImageCacheQueryCompletionBlock)doneBlock;
/**
* Asynchronously queries the cache with operation and call the completion when done.
*
* @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`.
* @param options A mask to specify options to use for this cache query
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param doneBlock The completion block. Will not get called if the operation is cancelled
*
* @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancellederation, will callback immediately when cancelled
* @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior.
*/
- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context done:(nullable SDImageCacheQueryCompletionBlock)doneBlock;
/**
* Asynchronously queries the cache with operation and call the completion when done.
*
* @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`.
* @param options A mask to specify options to use for this cache query
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param queryCacheType Specify where to query the cache from. By default we use `.all`, which means both memory cache and disk cache. You can choose to query memory only or disk only as well. Pass `.none` is invalid and callback with nil immediately.
* @param doneBlock The completion block. Will not get called if the operation is cancelled
*
* @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled
* @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior.
*/
- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock;
/**
* Synchronously query the memory cache.
*
* @param key The unique key used to store the image
* @return The image for the given key, or nil if not found.
*/
- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key;
/**
* Synchronously query the disk cache.
*
* @param key The unique key used to store the image
* @return The image for the given key, or nil if not found.
*/
- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key;
/**
* Synchronously query the disk cache. With the options and context which may effect the image generation. (Such as transformer, animated image, thumbnail, etc)
*
* @param key The unique key used to store the image
* @param options A mask to specify options to use for this cache query
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @return The image for the given key, or nil if not found.
*/
- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context;
/**
* Synchronously query the cache (memory and or disk) after checking the memory cache.
*
* @param key The unique key used to store the image
* @return The image for the given key, or nil if not found.
*/
- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key;
/**
* Synchronously query the cache (memory and or disk) after checking the memory cache. With the options and context which may effect the image generation. (Such as transformer, animated image, thumbnail, etc)
*
* @param key The unique key used to store the image
* @param options A mask to specify options to use for this cache query
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @return The image for the given key, or nil if not found.
*/
- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context;
#pragma mark - Remove Ops
/**
* Asynchronously remove the image from memory and disk cache
*
* @param key The unique image cache key
* @param completion A block that should be executed after the image has been removed (optional)
*/
- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion;
/**
* Asynchronously remove the image from memory and optionally disk cache
*
* @param key The unique image cache key
* @param fromDisk Also remove cache entry from disk if YES. If NO, the completion block is called synchronously
* @param completion A block that should be executed after the image has been removed (optional)
*/
- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion;
/**
Synchronously remove the image from memory cache.
@param key The unique image cache key
*/
- (void)removeImageFromMemoryForKey:(nullable NSString *)key;
/**
Synchronously remove the image from disk cache.
@param key The unique image cache key
*/
- (void)removeImageFromDiskForKey:(nullable NSString *)key;
#pragma mark - Cache clean Ops
/**
* Synchronously Clear all memory cached images
*/
- (void)clearMemory;
/**
* Asynchronously clear all disk cached images. Non-blocking method - returns immediately.
* @param completion A block that should be executed after cache expiration completes (optional)
*/
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion;
/**
* Asynchronously remove all expired cached image from disk. Non-blocking method - returns immediately.
* @param completionBlock A block that should be executed after cache expiration completes (optional)
*/
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock;
#pragma mark - Cache Info
/**
* Get the total bytes size of images in the disk cache
*/
- (NSUInteger)totalDiskSize;
/**
* Get the number of images in the disk cache
*/
- (NSUInteger)totalDiskCount;
/**
* Asynchronously calculate the disk cache's size.
*/
- (void)calculateSizeWithCompletionBlock:(nullable SDImageCacheCalculateSizeBlock)completionBlock;
@end
/**
* SDImageCache is the built-in image cache implementation for web image manager. It adopts `SDImageCache` protocol to provide the function for web image manager to use for image loading process.
*/
@interface SDImageCache (SDImageCache) <SDImageCache>
@end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,153 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
/// Image Cache Expire Type
typedef NS_ENUM(NSUInteger, SDImageCacheConfigExpireType) {
/**
* When the image cache is accessed it will update this value
*/
SDImageCacheConfigExpireTypeAccessDate,
/**
* When the image cache is created or modified it will update this value (Default)
*/
SDImageCacheConfigExpireTypeModificationDate,
/**
* When the image cache is created it will update this value
*/
SDImageCacheConfigExpireTypeCreationDate,
/**
* When the image cache is created, modified, renamed, file attribute updated (like permission, xattr) it will update this value
*/
SDImageCacheConfigExpireTypeChangeDate,
};
/**
The class contains all the config for image cache
@note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well.
*/
@interface SDImageCacheConfig : NSObject <NSCopying>
/**
Gets the default cache config used for shared instance or initialization when it does not provide any cache config. Such as `SDImageCache.sharedImageCache`.
@note You can modify the property on default cache config, which can be used for later created cache instance. The already created cache instance does not get affected.
*/
@property (nonatomic, class, readonly, nonnull) SDImageCacheConfig *defaultCacheConfig;
/**
* Whether or not to disable iCloud backup
* Defaults to YES.
*/
@property (assign, nonatomic) BOOL shouldDisableiCloud;
/**
* Whether or not to use memory cache
* @note When the memory cache is disabled, the weak memory cache will also be disabled.
* Defaults to YES.
*/
@property (assign, nonatomic) BOOL shouldCacheImagesInMemory;
/*
* The option to control weak memory cache for images. When enable, `SDImageCache`'s memory cache will use a weak maptable to store the image at the same time when it stored to memory, and get removed at the same time.
* However when memory warning is triggered, since the weak maptable does not hold a strong reference to image instance, even when the memory cache itself is purged, some images which are held strongly by UIImageViews or other live instances can be recovered again, to avoid later re-query from disk cache or network. This may be helpful for the case, for example, when app enter background and memory is purged, cause cell flashing after re-enter foreground.
* When enabling this option, we will sync back the image from weak maptable to strong cache during next time top level `sd_setImage` function call.
* Defaults to NO (YES before 5.12.0 version). You can change this option dynamically.
*/
@property (assign, nonatomic) BOOL shouldUseWeakMemoryCache;
/**
* Whether or not to remove the expired disk data when application entering the background. (Not works for macOS)
* Defaults to YES.
*/
@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground;
/**
* Whether or not to remove the expired disk data when application been terminated. This operation is processed in sync to ensure clean up.
* Defaults to YES.
*/
@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenTerminate;
/**
* The reading options while reading cache from disk.
* Defaults to 0. You can set this to `NSDataReadingMappedIfSafe` to improve performance.
*/
@property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions;
/**
* The writing options while writing cache to disk.
* Defaults to `NSDataWritingAtomic`. You can set this to `NSDataWritingWithoutOverwriting` to prevent overwriting an existing file.
*/
@property (assign, nonatomic) NSDataWritingOptions diskCacheWritingOptions;
/**
* The maximum length of time to keep an image in the disk cache, in seconds.
* Setting this to a negative value means no expiring.
* Setting this to zero means that all cached files would be removed when do expiration check.
* Defaults to 1 week.
*/
@property (assign, nonatomic) NSTimeInterval maxDiskAge;
/**
* The maximum size of the disk cache, in bytes.
* Defaults to 0. Which means there is no cache size limit.
*/
@property (assign, nonatomic) NSUInteger maxDiskSize;
/**
* The maximum "total cost" of the in-memory image cache. The cost function is the bytes size held in memory.
* @note The memory cost is bytes size in memory, but not simple pixels count. For common ARGB8888 image, one pixel is 4 bytes (32 bits).
* Defaults to 0. Which means there is no memory cost limit.
*/
@property (assign, nonatomic) NSUInteger maxMemoryCost;
/**
* The maximum number of objects in-memory image cache should hold.
* Defaults to 0. Which means there is no memory count limit.
*/
@property (assign, nonatomic) NSUInteger maxMemoryCount;
/*
* The attribute which the clear cache will be checked against when clearing the disk cache
* Default is Access Date
*/
@property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType;
/**
* The custom file manager for disk cache. Pass nil to let disk cache choose the proper file manager.
* Defaults to nil.
* @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect.
* @note Since `NSFileManager` does not support `NSCopying`. We just pass this by reference during copying. So it's not recommend to set this value on `defaultCacheConfig`.
*/
@property (strong, nonatomic, nullable) NSFileManager *fileManager;
/**
* The dispatch queue attr for ioQueue. You can config the QoS and concurrent/serial to internal IO queue. The ioQueue is used by SDImageCache to access read/write for disk data.
* Defaults we use `DISPATCH_QUEUE_SERIAL`(NULL) under iOS 10, `DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL` above and equal iOS 10, using serial dispatch queue is to ensure single access for disk data. It's safe but may be slow.
* @note You can override this to use `DISPATCH_QUEUE_CONCURRENT`, use concurrent queue.
* @warning **MAKE SURE** to keep `diskCacheWritingOptions` to use `NSDataWritingAtomic`, or concurrent queue may cause corrupted disk data (because multiple threads read/write same file without atomic is not IO-safe).
* @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect.
*/
@property (strong, nonatomic, nullable) dispatch_queue_attr_t ioQueueAttributes;
/**
* The custom memory cache class. Provided class instance must conform to `SDMemoryCache` protocol to allow usage.
* Defaults to built-in `SDMemoryCache` class.
* @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect.
*/
@property (assign, nonatomic, nonnull) Class memoryCacheClass;
/**
* The custom disk cache class. Provided class instance must conform to `SDDiskCache` protocol to allow usage.
* Defaults to built-in `SDDiskCache` class.
* @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect.
*/
@property (assign ,nonatomic, nonnull) Class diskCacheClass;
@end

View File

@@ -0,0 +1,72 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCacheConfig.h"
#import "SDMemoryCache.h"
#import "SDDiskCache.h"
static SDImageCacheConfig *_defaultCacheConfig;
static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week
@implementation SDImageCacheConfig
+ (SDImageCacheConfig *)defaultCacheConfig {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_defaultCacheConfig = [SDImageCacheConfig new];
});
return _defaultCacheConfig;
}
- (instancetype)init {
if (self = [super init]) {
_shouldDisableiCloud = YES;
_shouldCacheImagesInMemory = YES;
_shouldUseWeakMemoryCache = NO;
_shouldRemoveExpiredDataWhenEnterBackground = YES;
_shouldRemoveExpiredDataWhenTerminate = YES;
_diskCacheReadingOptions = 0;
_diskCacheWritingOptions = NSDataWritingAtomic;
_maxDiskAge = kDefaultCacheMaxDiskAge;
_maxDiskSize = 0;
_diskCacheExpireType = SDImageCacheConfigExpireTypeAccessDate;
_fileManager = nil;
if (@available(iOS 10.0, tvOS 10.0, macOS 10.12, watchOS 3.0, *)) {
_ioQueueAttributes = DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL; // DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM
} else {
_ioQueueAttributes = DISPATCH_QUEUE_SERIAL; // NULL
}
_memoryCacheClass = [SDMemoryCache class];
_diskCacheClass = [SDDiskCache class];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
SDImageCacheConfig *config = [[[self class] allocWithZone:zone] init];
config.shouldDisableiCloud = self.shouldDisableiCloud;
config.shouldCacheImagesInMemory = self.shouldCacheImagesInMemory;
config.shouldUseWeakMemoryCache = self.shouldUseWeakMemoryCache;
config.shouldRemoveExpiredDataWhenEnterBackground = self.shouldRemoveExpiredDataWhenEnterBackground;
config.shouldRemoveExpiredDataWhenTerminate = self.shouldRemoveExpiredDataWhenTerminate;
config.diskCacheReadingOptions = self.diskCacheReadingOptions;
config.diskCacheWritingOptions = self.diskCacheWritingOptions;
config.maxDiskAge = self.maxDiskAge;
config.maxDiskSize = self.maxDiskSize;
config.maxMemoryCost = self.maxMemoryCost;
config.maxMemoryCount = self.maxMemoryCount;
config.diskCacheExpireType = self.diskCacheExpireType;
config.fileManager = self.fileManager; // NSFileManager does not conform to NSCopying, just pass the reference
config.ioQueueAttributes = self.ioQueueAttributes; // Pass the reference
config.memoryCacheClass = self.memoryCacheClass;
config.diskCacheClass = self.diskCacheClass;
return config;
}
@end

View File

@@ -0,0 +1,179 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDWebImageOperation.h"
#import "SDWebImageDefine.h"
#import "SDImageCoder.h"
/// Image Cache Type
typedef NS_ENUM(NSInteger, SDImageCacheType) {
/**
* For query and contains op in response, means the image isn't available in the image cache
* For op in request, this type is not available and take no effect.
*/
SDImageCacheTypeNone,
/**
* For query and contains op in response, means the image was obtained from the disk cache.
* For op in request, means process only disk cache.
*/
SDImageCacheTypeDisk,
/**
* For query and contains op in response, means the image was obtained from the memory cache.
* For op in request, means process only memory cache.
*/
SDImageCacheTypeMemory,
/**
* For query and contains op in response, this type is not available and take no effect.
* For op in request, means process both memory cache and disk cache.
*/
SDImageCacheTypeAll
};
typedef void(^SDImageCacheCheckCompletionBlock)(BOOL isInCache);
typedef void(^SDImageCacheQueryDataCompletionBlock)(NSData * _Nullable data);
typedef void(^SDImageCacheCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
typedef NSString * _Nullable (^SDImageCacheAdditionalCachePathBlock)(NSString * _Nonnull key);
typedef void(^SDImageCacheQueryCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType);
typedef void(^SDImageCacheContainsCompletionBlock)(SDImageCacheType containsCacheType);
/**
This is the built-in decoding process for image query from cache.
@note If you want to implement your custom loader with `queryImageForKey:options:context:completion:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image.
@param imageData The image data from the cache. Should not be nil
@param cacheKey The image cache key from the input. Should not be nil
@param options The options arg from the input
@param context The context arg from the input
@return The decoded image for current image data query from cache
*/
FOUNDATION_EXPORT UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context);
/// Get the decode options from the loading context options and cache key. This is the built-in translate between the web loading part to the decoding part (which does not depends on).
/// @param context The context arg from the input
/// @param options The options arg from the input
/// @param cacheKey The image cache key from the input. Should not be nil
FOUNDATION_EXPORT SDImageCoderOptions * _Nonnull SDGetDecodeOptionsFromContext(SDWebImageContext * _Nullable context, SDWebImageOptions options, NSString * _Nonnull cacheKey);
/// Set the decode options to the loading context options. This is the built-in translate between the web loading part from the decoding part (which does not depends on).
/// @param mutableContext The context arg to override
/// @param mutableOptions The options arg to override
/// @param decodeOptions The image decoding options
FOUNDATION_EXPORT void SDSetDecodeOptionsToContext(SDWebImageMutableContext * _Nonnull mutableContext, SDWebImageOptions * _Nonnull mutableOptions, SDImageCoderOptions * _Nonnull decodeOptions);
/**
This is the image cache protocol to provide custom image cache for `SDWebImageManager`.
Though the best practice to custom image cache, is to write your own class which conform `SDMemoryCache` or `SDDiskCache` protocol for `SDImageCache` class (See more on `SDImageCacheConfig.memoryCacheClass & SDImageCacheConfig.diskCacheClass`).
However, if your own cache implementation contains more advanced feature beyond `SDImageCache` itself, you can consider to provide this instead. For example, you can even use a cache manager like `SDImageCachesManager` to register multiple caches.
*/
@protocol SDImageCache <NSObject>
@required
/**
Query the cached image from image cache for given key. The operation can be used to cancel the query.
If image is cached in memory, completion is called synchronously, else asynchronously and depends on the options arg (See `SDWebImageQueryDiskSync`)
@param key The image cache key
@param options A mask to specify options to use for this query
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. Pass `.callbackQueue` to control callback queue
@param completionBlock The completion block. Will not get called if the operation is cancelled
@return The operation for this query
*/
- (nullable id<SDWebImageOperation>)queryImageForKey:(nullable NSString *)key
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock API_DEPRECATED_WITH_REPLACEMENT("queryImageForKey:options:context:cacheType:completion:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@optional
/**
Query the cached image from image cache for given key. The operation can be used to cancel the query.
If image is cached in memory, completion is called synchronously, else asynchronously and depends on the options arg (See `SDWebImageQueryDiskSync`)
@param key The image cache key
@param options A mask to specify options to use for this query
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. Pass `.callbackQueue` to control callback queue
@param cacheType Specify where to query the cache from. By default we use `.all`, which means both memory cache and disk cache. You can choose to query memory only or disk only as well. Pass `.none` is invalid and callback with nil immediately.
@param completionBlock The completion block. Will not get called if the operation is cancelled
@return The operation for this query
*/
- (nullable id<SDWebImageOperation>)queryImageForKey:(nullable NSString *)key
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock;
@required
/**
Store the image into image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously.
@param image The image to store
@param imageData The image data to be used for disk storage
@param key The image cache key
@param cacheType The image store op cache type
@param completionBlock A block executed after the operation is finished
*/
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED_WITH_REPLACEMENT("storeImage:imageData:forKey:options:context:cacheType:completion:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@optional
/**
Store the image into image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously.
@param image The image to store
@param imageData The image data to be used for disk storage
@param key The image cache key
@param options A mask to specify options to use for this store
@param context The context options to use. Pass `.callbackQueue` to control callback queue
@param cacheType The image store op cache type
@param completionBlock A block executed after the operation is finished
*/
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDWebImageNoParamsBlock)completionBlock;
#pragma mark - Deprecated because SDWebImageManager does not use these APIs
/**
Remove the image from image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously.
@param key The image cache key
@param cacheType The image remove op cache type
@param completionBlock A block executed after the operation is finished
*/
- (void)removeImageForKey:(nullable NSString *)key
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
/**
Check if image cache contains the image for the given key (does not load the image). If image is cached in memory, completion is called synchronously, else asynchronously.
@param key The image cache key
@param cacheType The image contains op cache type
@param completionBlock A block executed after the operation is finished.
*/
- (void)containsImageForKey:(nullable NSString *)key
cacheType:(SDImageCacheType)cacheType
completion:(nullable SDImageCacheContainsCompletionBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
/**
Clear all the cached images for image cache. If cache type is memory only, completion is called synchronously, else asynchronously.
@param cacheType The image clear op cache type
@param completionBlock A block executed after the operation is finished
*/
- (void)clearWithCacheType:(SDImageCacheType)cacheType
completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@end

View File

@@ -0,0 +1,153 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCacheDefine.h"
#import "SDImageCodersManager.h"
#import "SDImageCoderHelper.h"
#import "SDAnimatedImage.h"
#import "UIImage+Metadata.h"
#import "SDInternalMacros.h"
#import "SDDeviceHelper.h"
#import <CoreServices/CoreServices.h>
SDImageCoderOptions * _Nonnull SDGetDecodeOptionsFromContext(SDWebImageContext * _Nullable context, SDWebImageOptions options, NSString * _Nonnull cacheKey) {
BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
NSNumber *scaleValue = context[SDWebImageContextImageScaleFactor];
CGFloat scale = scaleValue.doubleValue >= 1 ? scaleValue.doubleValue : SDImageScaleFactorForKey(cacheKey); // Use cache key to detect scale
NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio];
NSValue *thumbnailSizeValue;
BOOL shouldScaleDown = SD_OPTIONS_CONTAINS(options, SDWebImageScaleDownLargeImages);
NSNumber *scaleDownLimitBytesValue = context[SDWebImageContextImageScaleDownLimitBytes];
if (scaleDownLimitBytesValue == nil && shouldScaleDown) {
// Use the default limit bytes
scaleDownLimitBytesValue = @(SDImageCoderHelper.defaultScaleDownLimitBytes);
}
if (context[SDWebImageContextImageThumbnailPixelSize]) {
thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize];
}
NSString *typeIdentifierHint = context[SDWebImageContextImageTypeIdentifierHint];
NSString *fileExtensionHint;
if (!typeIdentifierHint) {
// UTI has high priority
fileExtensionHint = cacheKey.pathExtension; // without dot
if (fileExtensionHint.length == 0) {
// Ignore file extension which is empty
fileExtensionHint = nil;
}
}
// First check if user provided decode options
SDImageCoderMutableOptions *mutableCoderOptions;
if (context[SDWebImageContextImageDecodeOptions] != nil) {
mutableCoderOptions = [NSMutableDictionary dictionaryWithDictionary:context[SDWebImageContextImageDecodeOptions]];
} else {
mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:6];
}
// Some options need preserve the custom decode options
NSNumber *decodeToHDR = context[SDWebImageContextImageDecodeToHDR];
if (decodeToHDR == nil) {
decodeToHDR = mutableCoderOptions[SDImageCoderDecodeToHDR];
}
// Override individual options
mutableCoderOptions[SDImageCoderDecodeFirstFrameOnly] = @(decodeFirstFrame);
mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale);
mutableCoderOptions[SDImageCoderDecodePreserveAspectRatio] = preserveAspectRatioValue;
mutableCoderOptions[SDImageCoderDecodeThumbnailPixelSize] = thumbnailSizeValue;
mutableCoderOptions[SDImageCoderDecodeTypeIdentifierHint] = typeIdentifierHint;
mutableCoderOptions[SDImageCoderDecodeFileExtensionHint] = fileExtensionHint;
mutableCoderOptions[SDImageCoderDecodeScaleDownLimitBytes] = scaleDownLimitBytesValue;
mutableCoderOptions[SDImageCoderDecodeToHDR] = decodeToHDR;
return [mutableCoderOptions copy];
}
void SDSetDecodeOptionsToContext(SDWebImageMutableContext * _Nonnull mutableContext, SDWebImageOptions * _Nonnull mutableOptions, SDImageCoderOptions * _Nonnull decodeOptions) {
if ([decodeOptions[SDImageCoderDecodeFirstFrameOnly] boolValue]) {
*mutableOptions |= SDWebImageDecodeFirstFrameOnly;
} else {
*mutableOptions &= ~SDWebImageDecodeFirstFrameOnly;
}
mutableContext[SDWebImageContextImageScaleFactor] = decodeOptions[SDImageCoderDecodeScaleFactor];
mutableContext[SDWebImageContextImagePreserveAspectRatio] = decodeOptions[SDImageCoderDecodePreserveAspectRatio];
mutableContext[SDWebImageContextImageThumbnailPixelSize] = decodeOptions[SDImageCoderDecodeThumbnailPixelSize];
mutableContext[SDWebImageContextImageScaleDownLimitBytes] = decodeOptions[SDImageCoderDecodeScaleDownLimitBytes];
mutableContext[SDWebImageContextImageDecodeToHDR] = decodeOptions[SDImageCoderDecodeToHDR];
NSString *typeIdentifierHint = decodeOptions[SDImageCoderDecodeTypeIdentifierHint];
if (!typeIdentifierHint) {
NSString *fileExtensionHint = decodeOptions[SDImageCoderDecodeFileExtensionHint];
if (fileExtensionHint) {
typeIdentifierHint = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtensionHint, kUTTypeImage);
// Ignore dynamic UTI
if (UTTypeIsDynamic((__bridge CFStringRef)typeIdentifierHint)) {
typeIdentifierHint = nil;
}
}
}
mutableContext[SDWebImageContextImageTypeIdentifierHint] = typeIdentifierHint;
}
UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
NSCParameterAssert(imageData);
NSCParameterAssert(cacheKey);
UIImage *image;
SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey);
BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue];
// Grab the image coder
id<SDImageCoder> imageCoder = context[SDWebImageContextImageCoder];
if (!imageCoder) {
imageCoder = [SDImageCodersManager sharedManager];
}
if (!decodeFirstFrame) {
Class animatedImageClass = context[SDWebImageContextAnimatedImageClass];
// check whether we should use `SDAnimatedImage`
if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) {
image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions];
if (image) {
// Preload frames if supported
if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) {
[((id<SDAnimatedImage>)image) preloadAllFrames];
}
} else {
// Check image class matching
if (options & SDWebImageMatchAnimatedImageClass) {
return nil;
}
}
}
}
if (!image) {
image = [imageCoder decodedImageWithData:imageData options:coderOptions];
}
if (image) {
SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic;
NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy];
if (policyValue != nil) {
policy = policyValue.unsignedIntegerValue;
}
// TODO: Deprecated, remove in SD 6.0...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) {
policy = SDImageForceDecodePolicyNever;
}
#pragma clang diagnostic pop
image = [SDImageCoderHelper decodedImageWithImage:image policy:policy];
// assign the decode options, to let manager check whether to re-decode if needed
image.sd_decodeOptions = coderOptions;
}
return image;
}

View File

@@ -0,0 +1,81 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageCacheDefine.h"
/// Policy for cache operation
typedef NS_ENUM(NSUInteger, SDImageCachesManagerOperationPolicy) {
SDImageCachesManagerOperationPolicySerial, // process all caches serially (from the highest priority to the lowest priority cache by order)
SDImageCachesManagerOperationPolicyConcurrent, // process all caches concurrently
SDImageCachesManagerOperationPolicyHighestOnly, // process the highest priority cache only
SDImageCachesManagerOperationPolicyLowestOnly // process the lowest priority cache only
};
/**
A caches manager to manage multiple caches.
*/
@interface SDImageCachesManager : NSObject <SDImageCache>
/**
Returns the global shared caches manager instance. By default we will set [`SDImageCache.sharedImageCache`] into the caches array.
*/
@property (nonatomic, class, readonly, nonnull) SDImageCachesManager *sharedManager;
// These are op policy for cache manager.
/**
Operation policy for query op.
Defaults to `Serial`, means query all caches serially (one completion called then next begin) until one cache query success (`image` != nil).
*/
@property (nonatomic, assign) SDImageCachesManagerOperationPolicy queryOperationPolicy;
/**
Operation policy for store op.
Defaults to `HighestOnly`, means store to the highest priority cache only.
*/
@property (nonatomic, assign) SDImageCachesManagerOperationPolicy storeOperationPolicy;
/**
Operation policy for remove op.
Defaults to `Concurrent`, means remove all caches concurrently.
*/
@property (nonatomic, assign) SDImageCachesManagerOperationPolicy removeOperationPolicy;
/**
Operation policy for contains op.
Defaults to `Serial`, means check all caches serially (one completion called then next begin) until one cache check success (`containsCacheType` != None).
*/
@property (nonatomic, assign) SDImageCachesManagerOperationPolicy containsOperationPolicy;
/**
Operation policy for clear op.
Defaults to `Concurrent`, means clear all caches concurrently.
*/
@property (nonatomic, assign) SDImageCachesManagerOperationPolicy clearOperationPolicy;
/**
All caches in caches manager. The caches array is a priority queue, which means the later added cache will have the highest priority
*/
@property (nonatomic, copy, nullable) NSArray<id<SDImageCache>> *caches;
/**
Add a new cache to the end of caches array. Which has the highest priority.
@param cache cache
*/
- (void)addCache:(nonnull id<SDImageCache>)cache;
/**
Remove a cache in the caches array.
@param cache cache
*/
- (void)removeCache:(nonnull id<SDImageCache>)cache;
@end

View File

@@ -0,0 +1,560 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCachesManager.h"
#import "SDImageCachesManagerOperation.h"
#import "SDImageCache.h"
#import "SDInternalMacros.h"
@interface SDImageCachesManager ()
@property (nonatomic, strong, nonnull) NSMutableArray<id<SDImageCache>> *imageCaches;
@end
@implementation SDImageCachesManager {
SD_LOCK_DECLARE(_cachesLock);
}
+ (SDImageCachesManager *)sharedManager {
static dispatch_once_t onceToken;
static SDImageCachesManager *manager;
dispatch_once(&onceToken, ^{
manager = [[SDImageCachesManager alloc] init];
});
return manager;
}
- (instancetype)init {
self = [super init];
if (self) {
self.queryOperationPolicy = SDImageCachesManagerOperationPolicySerial;
self.storeOperationPolicy = SDImageCachesManagerOperationPolicyHighestOnly;
self.removeOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent;
self.containsOperationPolicy = SDImageCachesManagerOperationPolicySerial;
self.clearOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent;
// initialize with default image caches
_imageCaches = [NSMutableArray arrayWithObject:[SDImageCache sharedImageCache]];
SD_LOCK_INIT(_cachesLock);
}
return self;
}
- (NSArray<id<SDImageCache>> *)caches {
SD_LOCK(_cachesLock);
NSArray<id<SDImageCache>> *caches = [_imageCaches copy];
SD_UNLOCK(_cachesLock);
return caches;
}
- (void)setCaches:(NSArray<id<SDImageCache>> *)caches {
SD_LOCK(_cachesLock);
[_imageCaches removeAllObjects];
if (caches.count) {
[_imageCaches addObjectsFromArray:caches];
}
SD_UNLOCK(_cachesLock);
}
#pragma mark - Cache IO operations
- (void)addCache:(id<SDImageCache>)cache {
if (![cache conformsToProtocol:@protocol(SDImageCache)]) {
return;
}
SD_LOCK(_cachesLock);
[_imageCaches addObject:cache];
SD_UNLOCK(_cachesLock);
}
- (void)removeCache:(id<SDImageCache>)cache {
if (![cache conformsToProtocol:@protocol(SDImageCache)]) {
return;
}
SD_LOCK(_cachesLock);
[_imageCaches removeObject:cache];
SD_UNLOCK(_cachesLock);
}
#pragma mark - SDImageCache
- (id<SDWebImageOperation>)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context completion:(SDImageCacheQueryCompletionBlock)completionBlock {
return [self queryImageForKey:key options:options context:context cacheType:SDImageCacheTypeAll completion:completionBlock];
}
- (id<SDWebImageOperation>)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock {
if (!key) {
return nil;
}
NSArray<id<SDImageCache>> *caches = self.caches;
NSUInteger count = caches.count;
if (count == 0) {
return nil;
} else if (count == 1) {
return [caches.firstObject queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock];
}
switch (self.queryOperationPolicy) {
case SDImageCachesManagerOperationPolicyHighestOnly: {
id<SDImageCache> cache = caches.lastObject;
return [cache queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyLowestOnly: {
id<SDImageCache> cache = caches.firstObject;
return [cache queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyConcurrent: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self concurrentQueryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
return operation;
}
break;
case SDImageCachesManagerOperationPolicySerial: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self serialQueryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
return operation;
}
break;
default:
return nil;
break;
}
}
- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock {
[self storeImage:image imageData:imageData forKey:key options:0 context:nil cacheType:cacheType completion:completionBlock];
}
- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock {
if (!key) {
return;
}
NSArray<id<SDImageCache>> *caches = self.caches;
NSUInteger count = caches.count;
if (count == 0) {
return;
} else if (count == 1) {
[caches.firstObject storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock];
return;
}
switch (self.storeOperationPolicy) {
case SDImageCachesManagerOperationPolicyHighestOnly: {
id<SDImageCache> cache = caches.lastObject;
[cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyLowestOnly: {
id<SDImageCache> cache = caches.firstObject;
[cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyConcurrent: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self concurrentStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
}
break;
case SDImageCachesManagerOperationPolicySerial: {
[self serialStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator];
}
break;
default:
break;
}
}
- (void)removeImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock {
if (!key) {
return;
}
NSArray<id<SDImageCache>> *caches = self.caches;
NSUInteger count = caches.count;
if (count == 0) {
return;
} else if (count == 1) {
[caches.firstObject removeImageForKey:key cacheType:cacheType completion:completionBlock];
return;
}
switch (self.removeOperationPolicy) {
case SDImageCachesManagerOperationPolicyHighestOnly: {
id<SDImageCache> cache = caches.lastObject;
[cache removeImageForKey:key cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyLowestOnly: {
id<SDImageCache> cache = caches.firstObject;
[cache removeImageForKey:key cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyConcurrent: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self concurrentRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
}
break;
case SDImageCachesManagerOperationPolicySerial: {
[self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator];
}
break;
default:
break;
}
}
- (void)containsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock {
if (!key) {
return;
}
NSArray<id<SDImageCache>> *caches = self.caches;
NSUInteger count = caches.count;
if (count == 0) {
return;
} else if (count == 1) {
[caches.firstObject containsImageForKey:key cacheType:cacheType completion:completionBlock];
return;
}
switch (self.clearOperationPolicy) {
case SDImageCachesManagerOperationPolicyHighestOnly: {
id<SDImageCache> cache = caches.lastObject;
[cache containsImageForKey:key cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyLowestOnly: {
id<SDImageCache> cache = caches.firstObject;
[cache containsImageForKey:key cacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyConcurrent: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self concurrentContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
}
break;
case SDImageCachesManagerOperationPolicySerial: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
}
break;
default:
break;
}
}
- (void)clearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock {
NSArray<id<SDImageCache>> *caches = self.caches;
NSUInteger count = caches.count;
if (count == 0) {
return;
} else if (count == 1) {
[caches.firstObject clearWithCacheType:cacheType completion:completionBlock];
return;
}
switch (self.clearOperationPolicy) {
case SDImageCachesManagerOperationPolicyHighestOnly: {
id<SDImageCache> cache = caches.lastObject;
[cache clearWithCacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyLowestOnly: {
id<SDImageCache> cache = caches.firstObject;
[cache clearWithCacheType:cacheType completion:completionBlock];
}
break;
case SDImageCachesManagerOperationPolicyConcurrent: {
SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new];
[operation beginWithTotalCount:caches.count];
[self concurrentClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation];
}
break;
case SDImageCachesManagerOperationPolicySerial: {
[self serialClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator];
}
break;
default:
break;
}
}
#pragma mark - Concurrent Operation
- (void)concurrentQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
for (id<SDImageCache> cache in enumerator) {
[cache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (image) {
// Success
[operation done];
if (completionBlock) {
completionBlock(image, data, cacheType);
}
return;
}
if (operation.pendingCount == 0) {
// Complete
[operation done];
if (completionBlock) {
completionBlock(nil, nil, SDImageCacheTypeNone);
}
}
}];
}
}
- (void)concurrentStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
for (id<SDImageCache> cache in enumerator) {
[cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:^{
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (operation.pendingCount == 0) {
// Complete
[operation done];
if (completionBlock) {
completionBlock();
}
}
}];
}
}
- (void)concurrentRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
for (id<SDImageCache> cache in enumerator) {
[cache removeImageForKey:key cacheType:cacheType completion:^{
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (operation.pendingCount == 0) {
// Complete
[operation done];
if (completionBlock) {
completionBlock();
}
}
}];
}
}
- (void)concurrentContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
for (id<SDImageCache> cache in enumerator) {
[cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) {
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (containsCacheType != SDImageCacheTypeNone) {
// Success
[operation done];
if (completionBlock) {
completionBlock(containsCacheType);
}
return;
}
if (operation.pendingCount == 0) {
// Complete
[operation done];
if (completionBlock) {
completionBlock(SDImageCacheTypeNone);
}
}
}];
}
}
- (void)concurrentClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
for (id<SDImageCache> cache in enumerator) {
[cache clearWithCacheType:cacheType completion:^{
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (operation.pendingCount == 0) {
// Complete
[operation done];
if (completionBlock) {
completionBlock();
}
}
}];
}
}
#pragma mark - Serial Operation
- (void)serialQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
id<SDImageCache> cache = enumerator.nextObject;
if (!cache) {
// Complete
[operation done];
if (completionBlock) {
completionBlock(nil, nil, SDImageCacheTypeNone);
}
return;
}
@weakify(self);
[cache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
@strongify(self);
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (image) {
// Success
[operation done];
if (completionBlock) {
completionBlock(image, data, cacheType);
}
return;
}
// Next
[self serialQueryImageForKey:key options:options context:context cacheType:queryCacheType completion:completionBlock enumerator:enumerator operation:operation];
}];
}
- (void)serialStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator {
NSParameterAssert(enumerator);
id<SDImageCache> cache = enumerator.nextObject;
if (!cache) {
// Complete
if (completionBlock) {
completionBlock();
}
return;
}
@weakify(self);
[cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:^{
@strongify(self);
// Next
[self serialStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:enumerator];
}];
}
- (void)serialRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator {
NSParameterAssert(enumerator);
id<SDImageCache> cache = enumerator.nextObject;
if (!cache) {
// Complete
if (completionBlock) {
completionBlock();
}
return;
}
@weakify(self);
[cache removeImageForKey:key cacheType:cacheType completion:^{
@strongify(self);
// Next
[self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator];
}];
}
- (void)serialContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator operation:(SDImageCachesManagerOperation *)operation {
NSParameterAssert(enumerator);
NSParameterAssert(operation);
id<SDImageCache> cache = enumerator.nextObject;
if (!cache) {
// Complete
[operation done];
if (completionBlock) {
completionBlock(SDImageCacheTypeNone);
}
return;
}
@weakify(self);
[cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) {
@strongify(self);
if (operation.isCancelled) {
// Cancelled
return;
}
if (operation.isFinished) {
// Finished
return;
}
[operation completeOne];
if (containsCacheType != SDImageCacheTypeNone) {
// Success
[operation done];
if (completionBlock) {
completionBlock(containsCacheType);
}
return;
}
// Next
[self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator operation:operation];
}];
}
- (void)serialClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator<id<SDImageCache>> *)enumerator {
NSParameterAssert(enumerator);
id<SDImageCache> cache = enumerator.nextObject;
if (!cache) {
// Complete
if (completionBlock) {
completionBlock();
}
return;
}
@weakify(self);
[cache clearWithCacheType:cacheType completion:^{
@strongify(self);
// Next
[self serialClearWithCacheType:cacheType completion:completionBlock enumerator:enumerator];
}];
}
@end

View File

@@ -0,0 +1,347 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "NSData+ImageContentType.h"
#import "SDImageFrame.h"
/// Image Decoding/Encoding Options
typedef NSString * SDImageCoderOption NS_STRING_ENUM;
typedef NSDictionary<SDImageCoderOption, id> SDImageCoderOptions;
typedef NSMutableDictionary<SDImageCoderOption, id> SDImageCoderMutableOptions;
#pragma mark - Image Decoding Options
// These options are for image decoding
/**
A Boolean value indicating whether to decode the first frame only for animated image during decoding. (NSNumber). If not provide, decode animated image if need.
@note works for `SDImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeFirstFrameOnly;
/**
A CGFloat value which is greater than or equal to 1.0. This value specify the image scale factor for decoding. If not provide, use 1.0. (NSNumber)
@note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeScaleFactor;
/**
A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format).
Defaults to YES.
@note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodePreserveAspectRatio;
/**
A CGSize value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.preserveAspectRatio`) the value size.
Defaults to CGSizeZero, which means no thumbnail generation at all.
@note Supports for animated image as well.
@note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both.
@note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeThumbnailPixelSize;
/**
A NSString value indicating the source image's file extension. Example: "jpg", "nef", "tif", don't prefix the dot
Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF
Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser
@note However, different UTType may share the same file extension, like `public.jpeg` and `public.jpeg-2000` both use `.jpg`. If you want detail control, use `TypeIdentifierHint` below
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeFileExtensionHint;
/**
A NSString value (UTI) indicating the source image's file extension. Example: "public.jpeg-2000", "com.nikon.raw-image", "public.tiff"
Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF
Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser
@note If you provide `TypeIdentifierHint`, the `FileExtensionHint` option above will be ignored (because UTType has high priority)
@note If you really don't want any hint which effect the image result, pass `NSNull.null` instead
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeTypeIdentifierHint;
/**
A BOOL value indicating whether to use lazy-decoding. Defaults to NO on animated image coder, but defaults to YES on static image coder.
CGImageRef, this image object typically support lazy-decoding, via the `CGDataProviderCreateDirectAccess` or `CGDataProviderCreateSequential`
Which allows you to provide a lazy-called callback to access bitmap buffer, so that you can achieve lazy-decoding when consumer actually need bitmap buffer
UIKit on iOS use heavy on this and ImageIO codec prefers to lazy-decoding for common Hardware-Accelerate format like JPEG/PNG/HEIC
But however, the consumer may access bitmap buffer when running on main queue, like CoreAnimation layer render image. So this is a trade-off
You can force us to disable the lazy-decoding and always allocate bitmap buffer on RAM, but this may have higher ratio of OOM (out of memory)
@note The default value is NO for animated image coder (means `animatedImageFrameAtIndex:`)
@note The default value is YES for static image coder (means `decodedImageWithData:`)
@note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeUseLazyDecoding;
/**
A NSUInteger value to provide the limit bytes during decoding. This can help to avoid OOM on large frame count animated image or large pixel static image when you don't know how much RAM it occupied before decoding
The decoder will do these logic based on limit bytes:
1. Get the total frame count (static image means 1)
2. Calculate the `framePixelSize` width/height to `sqrt(limitBytes / frameCount / bytesPerPixel)`, keeping aspect ratio (at least 1x1)
3. If the `framePixelSize < originalImagePixelSize`, then do thumbnail decoding (see `SDImageCoderDecodeThumbnailPixelSize`) use the `framePixelSize` and `preseveAspectRatio = YES`
4. Else, use the full pixel decoding (small than limit bytes)
5. Whatever result, this does not effect the animated/static behavior of image. So even if you set `limitBytes = 1 && frameCount = 100`, we will stll create animated image with each frame `1x1` pixel size.
@note You can use the logic from `+[SDImageCoder scaledSizeWithImageSize:limitBytes:bytesPerPixel:frameCount:]`
@note This option has higher priority than `.decodeThumbnailPixelSize`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeScaleDownLimitBytes;
/**
A Boolean (`SDImageHDRType.rawValue`) value (stored inside NSNumber) to provide converting to HDR during decoding. Currently if number is 0 (`SDImageHDRTypeSDR`), use SDR, else use HDR. But we may extend this option to represent `SDImageHDRType` all cases in the future (means, think this options as uint number, but not actual boolean)
@note Supported by iOS 17 and above when using ImageIO coder (third-party coder can support lower firmware)
Defaults to @(NO), decoder will automatically convert SDR.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeToHDR;
#pragma mark - Image Encoding Options
/**
A NSUInteger (`SDImageHDRType.rawValue`) value (stored inside NSNumber) to provide converting to HDR during encoding. Read the below carefully to choose the value.
@note 0(`SDImageHDRTypeSDR`) means SDR; 1(`SDImageHDRTypeISOHDR`) means ISO HDR (at least using 10 bits per components or above, supported by AVIF/HEIF/JPEG-XL); 2(`SDImageHDRTypeISOGainMap`) means ISO Gain Map HDR (may use 8 bits per components, supported by AVIF/HEIF/JPEG-XL, as well as traditional JPEG)
@note Gain Map like a mask image with metadata, which contains the depth/bright information for pixels (1/4 resolution), which used to convert between HDR and SDR.
@note If you use CIImage as HDR pipeline, you can export as CGImage for encoding. (But it's also recommanded to use CIImage's `JPEGRepresentationOfImage` or `HEIFRepresentationOfImage`)
@note Supported by iOS 18 and above when using ImageIO coder (third-party coder can support lower firmware)
Defaults to @(0), encoder will automatically convert SDR.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeToHDR;
/**
A Boolean value indicating whether to encode the first frame only for animated image during encoding. (NSNumber). If not provide, encode animated image if need.
@note works for `SDImageCoder`.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeFirstFrameOnly;
/**
A double value between 0.0-1.0 indicating the encode compression quality to produce the image data. 1.0 resulting in no compression and 0.0 resulting in the maximum compression possible. If not provide, use 1.0. (NSNumber)
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeCompressionQuality;
/**
A UIColor(NSColor) value to used for non-alpha image encoding when the input image has alpha channel, the background color will be used to compose the alpha one. If not provide, use white color.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeBackgroundColor;
/**
A CGSize value indicating the max image resolution in pixels during encoding. For vector image, this also effect the output vector data information about width and height. The encoder will not generate the encoded image larger than this limit. Note it always use the aspect ratio of input image..
Defaults to CGSizeZero, which means no max size limit at all.
@note Supports for animated image as well.
@note The output image's width is limited to pixel size's width, the output image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeMaxPixelSize;
/**
A NSUInteger value specify the max output data bytes size after encoding. Some lossy format like JPEG/HEIF supports the hint for codec to automatically reduce the quality and match the file size you want. Note this option will override the `SDImageCoderEncodeCompressionQuality`, because now the quality is decided by the encoder. (NSNumber)
@note This is a hint, no guarantee for output size because of compression algorithm limit. And this options does not works for vector images.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeMaxFileSize;
/**
A Boolean value indicating the encoding format should contains a thumbnail image into the output data. Only some of image format (like JPEG/HEIF/AVIF) support this behavior. The embed thumbnail will be used during next time thumbnail decoding (provided `.thumbnailPixelSize`), which is faster than full image thumbnail decoding. (NSNumber)
Defaults to NO, which does not embed any thumbnail.
@note The thumbnail image's pixel size is not defined, the encoder can choose the proper pixel size which is suitable for encoding quality.
@note works for `SDImageCoder`
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeEmbedThumbnail;
/**
A SDWebImageContext object which hold the original context options from top-level API. (SDWebImageContext)
This option is ignored for all built-in coders and take no effect.
But this may be useful for some custom coders, because some business logic may dependent on things other than image or image data information only.
Only the unknown context from top-level API (See SDWebImageDefine.h) may be passed in during image loading.
See `SDWebImageContext` for more detailed information.
@warning Deprecated. This does nothing from 5.14.0. Use `SDWebImageContextImageDecodeOptions` to pass additional information in top-level API, and use `SDImageCoderOptions` to retrieve options from coder.
*/
FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderWebImageContext API_DEPRECATED("No longer supported. Use SDWebImageContextDecodeOptions in loader API to provide options. Use SDImageCoderOptions in coder API to retrieve options.", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0));
#pragma mark - Coder
/**
This is the image coder protocol to provide custom image decoding/encoding.
These methods are all required to implement.
@note Pay attention that these methods are not called from main queue.
*/
@protocol SDImageCoder <NSObject>
@required
#pragma mark - Decoding
/**
Returns YES if this coder can decode some data. Otherwise, the data should be passed to another coder.
@param data The image data so we can look at it
@return YES if this coder can decode the data, NO otherwise
*/
- (BOOL)canDecodeFromData:(nullable NSData *)data;
/**
Decode the image data to image.
@note This protocol may supports decode animated image frames. You can use `+[SDImageCoderHelper animatedImageWithFrames:]` to produce an animated image with frames.
@param data The image data to be decoded
@param options A dictionary containing any decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for image. Pass @{SDImageCoderDecodeFirstFrameOnly: @(YES)} to decode the first frame only.
@return The decoded image from data
*/
- (nullable UIImage *)decodedImageWithData:(nullable NSData *)data
options:(nullable SDImageCoderOptions *)options;
#pragma mark - Encoding
/**
Returns YES if this coder can encode some image. Otherwise, it should be passed to another coder.
For custom coder which introduce new image format, you'd better define a new `SDImageFormat` using like this. If you're creating public coder plugin for new image format, also update `https://github.com/rs/SDWebImage/wiki/Coder-Plugin-List` to avoid same value been defined twice.
* @code
static const SDImageFormat SDImageFormatHEIF = 10;
* @endcode
@param format The image format
@return YES if this coder can encode the image, NO otherwise
*/
- (BOOL)canEncodeToFormat:(SDImageFormat)format NS_SWIFT_NAME(canEncode(to:));
/**
Encode the image to image data.
@note This protocol may supports encode animated image frames. You can use `+[SDImageCoderHelper framesFromAnimatedImage:]` to assemble an animated image with frames. But this consume time is not always reversible. In 5.15.0, we introduce `encodedDataWithFrames` API for better animated image encoding. Use that instead.
@note Which means, this just forward to `encodedDataWithFrames([SDImageFrame(image: image, duration: 0], image.sd_imageLoopCount))`
@param image The image to be encoded
@param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible
@param options A dictionary containing any encoding options. Pass @{SDImageCoderEncodeCompressionQuality: @(1)} to specify compression quality.
@return The encoded image data
*/
- (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image
format:(SDImageFormat)format
options:(nullable SDImageCoderOptions *)options;
#pragma mark - Animated Encoding
@optional
/**
Encode the animated image frames to image data.
@param frames The animated image frames to be encoded, should be at least 1 element, or it will fallback to static image encode.
@param loopCount The final animated image loop count. 0 means infinity loop. This config ignore each frame's `sd_imageLoopCount`
@param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible
@param options A dictionary containing any encoding options. Pass @{SDImageCoderEncodeCompressionQuality: @(1)} to specify compression quality.
@return The encoded image data
*/
- (nullable NSData *)encodedDataWithFrames:(nonnull NSArray<SDImageFrame *>*)frames
loopCount:(NSUInteger)loopCount
format:(SDImageFormat)format
options:(nullable SDImageCoderOptions *)options;
@end
#pragma mark - Progressive Coder
/**
This is the image coder protocol to provide custom progressive image decoding.
These methods are all required to implement.
@note Pay attention that these methods are not called from main queue.
*/
@protocol SDProgressiveImageCoder <SDImageCoder>
@required
/**
Returns YES if this coder can incremental decode some data. Otherwise, it should be passed to another coder.
@param data The image data so we can look at it
@return YES if this coder can decode the data, NO otherwise
*/
- (BOOL)canIncrementalDecodeFromData:(nullable NSData *)data;
/**
Because incremental decoding need to keep the decoded context, we will alloc a new instance with the same class for each download operation to avoid conflicts
This init method should not return nil
@param options A dictionary containing any progressive decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive animated image (each frames should use the same scale).
@return A new instance to do incremental decoding for the specify image format
*/
- (nonnull instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options;
/**
Update the incremental decoding when new image data available
@param data The image data has been downloaded so far
@param finished Whether the download has finished
*/
- (void)updateIncrementalData:(nullable NSData *)data finished:(BOOL)finished;
/**
Incremental decode the current image data to image.
@note Due to the performance issue for progressive decoding and the integration for image view. This method may only return the first frame image even if the image data is animated image. If you want progressive animated image decoding, conform to `SDAnimatedImageCoder` protocol as well and use `animatedImageFrameAtIndex:` instead.
@param options A dictionary containing any progressive decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive image
@return The decoded image from current data
*/
- (nullable UIImage *)incrementalDecodedImageWithOptions:(nullable SDImageCoderOptions *)options;
@end
#pragma mark - Animated Image Provider
/**
This is the animated image protocol to provide the basic function for animated image rendering. It's adopted by `SDAnimatedImage` and `SDAnimatedImageCoder`
*/
@protocol SDAnimatedImageProvider <NSObject>
@required
/**
The original animated image data for current image. If current image is not an animated format, return nil.
We may use this method to grab back the original image data if need, such as NSCoding or compare.
@return The animated image data
*/
@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData;
/**
Total animated frame count.
If the frame count is less than 1, then the methods below will be ignored.
@return Total animated frame count.
*/
@property (nonatomic, assign, readonly) NSUInteger animatedImageFrameCount;
/**
Animation loop count, 0 means infinite looping.
@return Animation loop count
*/
@property (nonatomic, assign, readonly) NSUInteger animatedImageLoopCount;
/**
Returns the frame image from a specified index.
@note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's not recommend to store the images into array because it's memory consuming)
@param index Frame index (zero based).
@return Frame's image
*/
- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
/**
Returns the frames's duration from a specified index.
@note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's recommend to store the durations into array because it's not memory-consuming)
@param index Frame index (zero based).
@return Frame's duration
*/
- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index;
@end
#pragma mark - Animated Coder
/**
This is the animated image coder protocol for custom animated image class like `SDAnimatedImage`. Through it inherit from `SDImageCoder`. We currentlly only use the method `canDecodeFromData:` to detect the proper coder for specify animated image format.
*/
@protocol SDAnimatedImageCoder <SDImageCoder, SDAnimatedImageProvider>
@required
/**
Because animated image coder should keep the original data, we will alloc a new instance with the same class for the specify animated image data
The init method should return nil if it can't decode the specify animated image data to produce any frame.
After the instance created, we may call methods in `SDAnimatedImageProvider` to produce animated image frame.
@param data The animated image data to be decode
@param options A dictionary containing any animated decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for animated image (each frames should use the same scale).
@return A new instance to do animated decoding for specify image data
*/
- (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options;
@end

View File

@@ -0,0 +1,29 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCoder.h"
SDImageCoderOption const SDImageCoderDecodeFirstFrameOnly = @"decodeFirstFrameOnly";
SDImageCoderOption const SDImageCoderDecodeScaleFactor = @"decodeScaleFactor";
SDImageCoderOption const SDImageCoderDecodePreserveAspectRatio = @"decodePreserveAspectRatio";
SDImageCoderOption const SDImageCoderDecodeThumbnailPixelSize = @"decodeThumbnailPixelSize";
SDImageCoderOption const SDImageCoderDecodeFileExtensionHint = @"decodeFileExtensionHint";
SDImageCoderOption const SDImageCoderDecodeTypeIdentifierHint = @"decodeTypeIdentifierHint";
SDImageCoderOption const SDImageCoderDecodeUseLazyDecoding = @"decodeUseLazyDecoding";
SDImageCoderOption const SDImageCoderDecodeScaleDownLimitBytes = @"decodeScaleDownLimitBytes";
SDImageCoderOption const SDImageCoderDecodeToHDR = @"decodeToHDR";
SDImageCoderOption const SDImageCoderEncodeToHDR = @"encodeToHDR";
SDImageCoderOption const SDImageCoderEncodeFirstFrameOnly = @"encodeFirstFrameOnly";
SDImageCoderOption const SDImageCoderEncodeCompressionQuality = @"encodeCompressionQuality";
SDImageCoderOption const SDImageCoderEncodeBackgroundColor = @"encodeBackgroundColor";
SDImageCoderOption const SDImageCoderEncodeMaxPixelSize = @"encodeMaxPixelSize";
SDImageCoderOption const SDImageCoderEncodeMaxFileSize = @"encodeMaxFileSize";
SDImageCoderOption const SDImageCoderEncodeEmbedThumbnail = @"encodeEmbedThumbnail";
SDImageCoderOption const SDImageCoderWebImageContext = @"webImageContext";

View File

@@ -0,0 +1,250 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <ImageIO/ImageIO.h>
#import "SDWebImageCompat.h"
#import "SDImageFrame.h"
/// The options controls how we force pre-draw the image (to avoid lazy-decoding). Which need OS's framework compatibility
typedef NS_ENUM(NSUInteger, SDImageCoderDecodeSolution) {
/// automatically choose the solution based on image format, hardware, OS version. This keep balance for compatibility and performance. Default after SDWebImage 5.13.0
SDImageCoderDecodeSolutionAutomatic,
/// always use CoreGraphics to draw on bitmap context and trigger decode. Best compatibility. Default before SDWebImage 5.13.0
SDImageCoderDecodeSolutionCoreGraphics,
/// available on iOS/tvOS 15+, use UIKit's new CGImageDecompressor/CMPhoto to decode. Best performance. If failed, will fallback to CoreGraphics as well
SDImageCoderDecodeSolutionUIKit
};
/// The policy to force-decode the origin CGImage (produced by Image Coder Plugin)
/// Some CGImage may be lazy, or not lazy, but need extra copy to render on screen
/// The force-decode step help to `pre-process` to get the best suitable CGImage to render, which can increase frame rate
/// The downside is that force-decode may consume RAM and CPU, and may loss the `lazy` support (lazy CGImage can be purged when memory warning, and re-created if need), see more: `SDImageCoderDecodeUseLazyDecoding`
typedef NS_ENUM(NSUInteger, SDImageForceDecodePolicy) {
/// Based on input CGImage's colorspace, alignment, bitmapinfo, if it may trigger `CA::copy_image` extra copy, we will force-decode, else don't
SDImageForceDecodePolicyAutomatic,
/// Never force decode input CGImage
SDImageForceDecodePolicyNever,
/// Always force decode input CGImage (only once)
SDImageForceDecodePolicyAlways
};
/// These enum is used to represent the High Dynamic Range type during image encoding/decoding.
/// There are alao other HDR type in history before ISO Standard (ISO 21496-1), including Google and Apple's old OSs captured photos, but which is non-standard and we do not support.
typedef NS_ENUM(NSUInteger, SDImageHDRType) {
/// SDR, mostly only 8 bits color per components, RGBA8
SDImageHDRTypeSDR = 0,
/// ISO HDR (supported by modern format only, like HEIF/AVIF/JPEG-XL)
SDImageHDRTypeISOHDR = 1,
/// ISO Gain Map based HDR (supported by nearly all format, including tranditional JPEG, which stored the gain map into XMP)
SDImageHDRTypeISOGainMap = 2,
};
/// Byte alignment the bytes size with alignment
/// - Parameters:
/// - size: The bytes size
/// - alignment: The alignment, in bytes
static inline size_t SDByteAlign(size_t size, size_t alignment) {
return ((size + (alignment - 1)) / alignment) * alignment;
}
/// The pixel format about the information to call `CGImageCreate` suitable for current hardware rendering
typedef struct SDImagePixelFormat {
/// Typically is pre-multiplied RGBA8888 for alpha image, RGBX8888 for non-alpha image.
CGBitmapInfo bitmapInfo;
/// Typically is 32, the 8 pixels bytesPerRow.
size_t alignment;
} SDImagePixelFormat;
/**
Provide some common helper methods for building the image decoder/encoder.
*/
@interface SDImageCoderHelper : NSObject
/**
Return an animated image with frames array.
For UIKit, this will apply the patch and then create animated UIImage. The patch is because that `+[UIImage animatedImageWithImages:duration:]` just use the average of duration for each image. So it will not work if different frame has different duration. Therefore we repeat the specify frame for specify times to let it work.
For AppKit, NSImage does not support animates other than GIF. This will try to encode the frames to GIF format and then create an animated NSImage for rendering. Attention the animated image may loss some detail if the input frames contain full alpha channel because GIF only supports 1 bit alpha channel. (For 1 pixel, either transparent or not)
@param frames The frames array. If no frames or frames is empty, return nil
@return A animated image for rendering on UIImageView(UIKit) or NSImageView(AppKit)
*/
+ (UIImage * _Nullable)animatedImageWithFrames:(NSArray<SDImageFrame *> * _Nullable)frames;
/**
Return frames array from an animated image.
For UIKit, this will unapply the patch for the description above and then create frames array. This will also work for normal animated UIImage.
For AppKit, NSImage does not support animates other than GIF. This will try to decode the GIF imageRep and then create frames array.
@param animatedImage A animated image. If it's not animated, return nil
@return The frames array
*/
+ (NSArray<SDImageFrame *> * _Nullable)framesFromAnimatedImage:(UIImage * _Nullable)animatedImage NS_SWIFT_NAME(frames(from:));
#pragma mark - Preferred Rendering Format
/// For coders who use `CGImageCreate`, use the information below to create an effient CGImage which can be render on GPU without Core Animation's extra copy (`CA::Render::copy_image`), which can be debugged using `Color Copied Image` in Xcode Instruments
/// `CGImageCreate`'s `bytesPerRow`, `space`, `bitmapInfo` params should use the information below.
/**
Return the shared device-dependent RGB color space. This follows The Get Rule.
Because it's shared, you should not retain or release this object.
Typically is sRGB for iOS, screen color space (like Color LCD) for macOS.
@return The device-dependent RGB color space
*/
+ (CGColorSpaceRef _Nonnull)colorSpaceGetDeviceRGB CF_RETURNS_NOT_RETAINED;
/**
Tthis returns the pixel format **Preferred from current hardward && OS using runtime detection**
@param containsAlpha Whether the image to render contains alpha channel
*/
+ (SDImagePixelFormat)preferredPixelFormat:(BOOL)containsAlpha;
/**
Check whether CGImage is hardware supported to rendering on screen, without the trigger of `CA::Render::copy_image`
You can debug the copied image by using Xcode's `Color Copied Image`, the copied image will turn Cyan and occupy double RAM for bitmap buffer.
Typically, when the CGImage's using the method above (`colorspace` / `alignment` / `bitmapInfo`) can render withtout the copy.
*/
+ (BOOL)CGImageIsHardwareSupported:(_Nonnull CGImageRef)cgImage;
/**
Check whether CGImage contains alpha channel.
@param cgImage The CGImage
@return Return YES if CGImage contains alpha channel, otherwise return NO
*/
+ (BOOL)CGImageContainsAlpha:(_Nonnull CGImageRef)cgImage;
/**
Detect whether the CGImage is lazy and not-yet decoded. (lazy means, only when the caller access the underlying bitmap buffer via provider like `CGDataProviderCopyData` or `CGDataProviderRetainBytePtr`, the decoder will allocate memory, it's a lazy allocation)
The implementation use the Core Graphics internal to check whether the CGImage is `CGImageProvider` based, or `CGDataProvider` based. The `CGDataProvider` based is treated as non-lazy.
*/
+ (BOOL)CGImageIsLazy:(_Nonnull CGImageRef)cgImage;
/**
Check if the CGImage is using HDR color space.
@note This use the same implementation like Apple, to checkl if color space uses transfer functions defined in ITU Rec.2100
*/
+ (BOOL)CGImageIsHDR:(_Nonnull CGImageRef)cgImage;
/**
Create a decoded CGImage by the provided CGImage. This follows The Create Rule and you are response to call release after usage.
It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView.
@note This actually call `CGImageCreateDecoded:orientation:` with the Up orientation.
@param cgImage The CGImage
@return A new created decoded image
*/
+ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage CF_RETURNS_RETAINED;
/**
Create a decoded CGImage by the provided CGImage and orientation. This follows The Create Rule and you are response to call release after usage.
It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView.
@param cgImage The CGImage
@param orientation The EXIF image orientation.
@return A new created decoded image
*/
+ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage orientation:(CGImagePropertyOrientation)orientation CF_RETURNS_RETAINED;
/**
Create a scaled CGImage by the provided CGImage and size. This follows The Create Rule and you are response to call release after usage.
It will detect whether the image size matching the scale size, if not, stretch the image to the target size.
@note If you need to keep aspect ratio, you can calculate the scale size by using `scaledSizeWithImageSize` first.
@note This scale does not change bits per components (which means RGB888 in, RGB888 out), supports 8/16/32(float) bpc. But the method in UIImage+Transform does not gurantee this.
@note All supported CGImage pixel format: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB
@param cgImage The CGImage
@param size The scale size in pixel.
@return A new created scaled image
*/
+ (CGImageRef _Nullable)CGImageCreateScaled:(_Nonnull CGImageRef)cgImage size:(CGSize)size CF_RETURNS_RETAINED;
/** Scale the image size based on provided scale size, whether or not to preserve aspect ratio, whether or not to scale up.
@note For example, if you implements thumnail decoding, pass `shouldScaleUp` to NO to avoid the calculated size larger than image size.
@param imageSize The image size (in pixel or point defined by caller)
@param scaleSize The scale size (in pixel or point defined by caller)
@param preserveAspectRatio Whether or not to preserve aspect ratio
@param shouldScaleUp Whether or not to scale up (or scale down only)
*/
+ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize scaleSize:(CGSize)scaleSize preserveAspectRatio:(BOOL)preserveAspectRatio shouldScaleUp:(BOOL)shouldScaleUp;
/// Calculate the limited image size with the bytes, when using `SDImageCoderDecodeScaleDownLimitBytes`. This preserve aspect ratio and never scale up
/// @param imageSize The image size (in pixel or point defined by caller)
/// @param limitBytes The limit bytes
/// @param bytesPerPixel The bytes per pixel
/// @param frameCount The image frame count, 0 means 1 frame as well
+ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize limitBytes:(NSUInteger)limitBytes bytesPerPixel:(NSUInteger)bytesPerPixel frameCount:(NSUInteger)frameCount;
/**
Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image. On iOS 15+, this may use `UIImage.preparingForDisplay()` to use CMPhoto for better performance than the old solution.
@param image The image to be decoded
@note This translate to `decodedImageWithImage:policy:` with automatic policy
@return The decoded image
*/
+ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image;
/**
Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image. On iOS 15+, this may use `UIImage.preparingForDisplay()` to use CMPhoto for better performance than the old solution.
@param image The image to be decoded
@param policy The force decode policy to decode image, will effect the check whether input image need decode
@return The decoded image
*/
+ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image policy:(SDImageForceDecodePolicy)policy;
/**
Return the decoded and probably scaled down image by the provided image. If the image pixels bytes size large than the limit bytes, will try to scale down. Or just works as `decodedImageWithImage:`, never scale up.
@warning You should not pass too small bytes, the suggestion value should be larger than 1MB. Even we use Tile Decoding to avoid OOM, however, small bytes will consume much more CPU time because we need to iterate more times to draw each tile.
@param image The image to be decoded and scaled down
@param bytes The limit bytes size. Provide 0 to use the build-in limit.
@note This translate to `decodedAndScaledDownImageWithImage:limitBytes:policy:` with automatic policy
@return The decoded and probably scaled down image
*/
+ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes;
/**
Return the decoded and probably scaled down image by the provided image. If the image pixels bytes size large than the limit bytes, will try to scale down. Or just works as `decodedImageWithImage:`, never scale up.
@warning You should not pass too small bytes, the suggestion value should be larger than 1MB. Even we use Tile Decoding to avoid OOM, however, small bytes will consume much more CPU time because we need to iterate more times to draw each tile.
@param image The image to be decoded and scaled down
@param bytes The limit bytes size. Provide 0 to use the build-in limit.
@param policy The force decode policy to decode image, will effect the check whether input image need decode
@return The decoded and probably scaled down image
*/
+ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes policy:(SDImageForceDecodePolicy)policy;
/**
Control the default force decode solution. Available solutions in `SDImageCoderDecodeSolution`.
@note Defaults to `SDImageCoderDecodeSolutionAutomatic`, which prefers to use UIKit for JPEG/HEIF, and fallback on CoreGraphics. If you want control on your hand, set the other solution.
*/
@property (class, readwrite) SDImageCoderDecodeSolution defaultDecodeSolution;
/**
Control the default limit bytes to scale down largest images.
This value must be larger than 4 Bytes (at least 1x1 pixel). Defaults to 60MB on iOS/tvOS, 90MB on macOS, 30MB on watchOS.
*/
@property (class, readwrite) NSUInteger defaultScaleDownLimitBytes;
#if SD_UIKIT || SD_WATCH
/**
Convert an EXIF image orientation to an iOS one.
@param exifOrientation EXIF orientation
@return iOS orientation
*/
+ (UIImageOrientation)imageOrientationFromEXIFOrientation:(CGImagePropertyOrientation)exifOrientation NS_SWIFT_NAME(imageOrientation(from:));
/**
Convert an iOS orientation to an EXIF image orientation.
@param imageOrientation iOS orientation
@return EXIF orientation
*/
+ (CGImagePropertyOrientation)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation;
#endif
@end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageCoder.h"
/**
Global object holding the array of coders, so that we avoid passing them from object to object.
Uses a priority queue behind scenes, which means the latest added coders have the highest priority.
This is done so when encoding/decoding something, we go through the list and ask each coder if they can handle the current data.
That way, users can add their custom coders while preserving our existing prebuilt ones
Note: the `coders` getter will return the coders in their reversed order
Example:
- by default we internally set coders = `IOCoder`, `GIFCoder`, `APNGCoder`
- calling `coders` will return `@[IOCoder, GIFCoder, APNGCoder]`
- call `[addCoder:[MyCrazyCoder new]]`
- calling `coders` now returns `@[IOCoder, GIFCoder, APNGCoder, MyCrazyCoder]`
Coders
------
A coder must conform to the `SDImageCoder` protocol or even to `SDProgressiveImageCoder` if it supports progressive decoding
Conformance is important because that way, they will implement `canDecodeFromData` or `canEncodeToFormat`
Those methods are called on each coder in the array (using the priority order) until one of them returns YES.
That means that coder can decode that data / encode to that format
*/
@interface SDImageCodersManager : NSObject <SDImageCoder>
/**
Returns the global shared coders manager instance.
*/
@property (nonatomic, class, readonly, nonnull) SDImageCodersManager *sharedManager;
/**
All coders in coders manager. The coders array is a priority queue, which means the later added coder will have the highest priority
*/
@property (nonatomic, copy, nullable) NSArray<id<SDImageCoder>> *coders;
/**
Add a new coder to the end of coders array. Which has the highest priority.
@param coder coder
*/
- (void)addCoder:(nonnull id<SDImageCoder>)coder;
/**
Remove a coder in the coders array.
@param coder coder
*/
- (void)removeCoder:(nonnull id<SDImageCoder>)coder;
@end

View File

@@ -0,0 +1,145 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCodersManager.h"
#import "SDImageIOCoder.h"
#import "SDImageGIFCoder.h"
#import "SDImageAPNGCoder.h"
#import "SDImageHEICCoder.h"
#import "SDInternalMacros.h"
@interface SDImageCodersManager ()
@property (nonatomic, strong, nonnull) NSMutableArray<id<SDImageCoder>> *imageCoders;
@end
@implementation SDImageCodersManager {
SD_LOCK_DECLARE(_codersLock);
}
+ (nonnull instancetype)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (instancetype)init {
if (self = [super init]) {
// initialize with default coders
_imageCoders = [NSMutableArray arrayWithArray:@[[SDImageIOCoder sharedCoder], [SDImageGIFCoder sharedCoder], [SDImageAPNGCoder sharedCoder]]];
SD_LOCK_INIT(_codersLock);
}
return self;
}
- (NSArray<id<SDImageCoder>> *)coders {
SD_LOCK(_codersLock);
NSArray<id<SDImageCoder>> *coders = [_imageCoders copy];
SD_UNLOCK(_codersLock);
return coders;
}
- (void)setCoders:(NSArray<id<SDImageCoder>> *)coders {
SD_LOCK(_codersLock);
[_imageCoders removeAllObjects];
if (coders.count) {
[_imageCoders addObjectsFromArray:coders];
}
SD_UNLOCK(_codersLock);
}
#pragma mark - Coder IO operations
- (void)addCoder:(nonnull id<SDImageCoder>)coder {
if (![coder conformsToProtocol:@protocol(SDImageCoder)]) {
return;
}
SD_LOCK(_codersLock);
[_imageCoders addObject:coder];
SD_UNLOCK(_codersLock);
}
- (void)removeCoder:(nonnull id<SDImageCoder>)coder {
if (![coder conformsToProtocol:@protocol(SDImageCoder)]) {
return;
}
SD_LOCK(_codersLock);
[_imageCoders removeObject:coder];
SD_UNLOCK(_codersLock);
}
#pragma mark - SDImageCoder
- (BOOL)canDecodeFromData:(NSData *)data {
NSArray<id<SDImageCoder>> *coders = self.coders;
for (id<SDImageCoder> coder in coders.reverseObjectEnumerator) {
if ([coder canDecodeFromData:data]) {
return YES;
}
}
return NO;
}
- (BOOL)canEncodeToFormat:(SDImageFormat)format {
NSArray<id<SDImageCoder>> *coders = self.coders;
for (id<SDImageCoder> coder in coders.reverseObjectEnumerator) {
if ([coder canEncodeToFormat:format]) {
return YES;
}
}
return NO;
}
- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options {
if (!data) {
return nil;
}
UIImage *image;
NSArray<id<SDImageCoder>> *coders = self.coders;
for (id<SDImageCoder> coder in coders.reverseObjectEnumerator) {
if ([coder canDecodeFromData:data]) {
image = [coder decodedImageWithData:data options:options];
break;
}
}
return image;
}
- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options {
if (!image) {
return nil;
}
NSArray<id<SDImageCoder>> *coders = self.coders;
for (id<SDImageCoder> coder in coders.reverseObjectEnumerator) {
if ([coder canEncodeToFormat:format]) {
return [coder encodedDataWithImage:image format:format options:options];
}
}
return nil;
}
- (NSData *)encodedDataWithFrames:(NSArray<SDImageFrame *> *)frames loopCount:(NSUInteger)loopCount format:(SDImageFormat)format options:(SDImageCoderOptions *)options {
if (!frames || frames.count < 1) {
return nil;
}
NSArray<id<SDImageCoder>> *coders = self.coders;
for (id<SDImageCoder> coder in coders.reverseObjectEnumerator) {
if ([coder canEncodeToFormat:format]) {
if ([coder respondsToSelector:@selector(encodedDataWithFrames:loopCount:format:options:)]) {
return [coder encodedDataWithFrames:frames loopCount:loopCount format:format options:options];
}
}
}
return nil;
}
@end

View File

@@ -0,0 +1,44 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
/**
This class is used for creating animated images via `animatedImageWithFrames` in `SDImageCoderHelper`.
@note If you need to specify animated images loop count, use `sd_imageLoopCount` property in `UIImage+Metadata.h`.
*/
@interface SDImageFrame : NSObject
/**
The image of current frame. You should not set an animated image.
*/
@property (nonatomic, strong, readonly, nonnull) UIImage *image;
/**
The duration of current frame to be displayed. The number is seconds but not milliseconds. You should not set this to zero.
*/
@property (nonatomic, readonly, assign) NSTimeInterval duration;
/// Create a frame instance with specify image and duration
/// @param image current frame's image
/// @param duration current frame's duration
- (nonnull instancetype)initWithImage:(nonnull UIImage *)image duration:(NSTimeInterval)duration;
/**
Create a frame instance with specify image and duration
@param image current frame's image
@param duration current frame's duration
@return frame instance
*/
+ (nonnull instancetype)frameWithImage:(nonnull UIImage *)image duration:(NSTimeInterval)duration;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end

View File

@@ -0,0 +1,34 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageFrame.h"
@interface SDImageFrame ()
@property (nonatomic, strong, readwrite, nonnull) UIImage *image;
@property (nonatomic, readwrite, assign) NSTimeInterval duration;
@end
@implementation SDImageFrame
- (instancetype)initWithImage:(UIImage *)image duration:(NSTimeInterval)duration {
self = [super init];
if (self) {
_image = image;
_duration = duration;
}
return self;
}
+ (instancetype)frameWithImage:(UIImage *)image duration:(NSTimeInterval)duration {
SDImageFrame *frame = [[SDImageFrame alloc] initWithImage:image duration:duration];
return frame;
}
@end

View File

@@ -0,0 +1,22 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageIOAnimatedCoder.h"
/**
Built in coder using ImageIO that supports animated GIF encoding/decoding
@note `SDImageIOCoder` supports GIF but only as static (will use the 1st frame).
@note Use `SDImageGIFCoder` for fully animated GIFs. For `UIImageView`, it will produce animated `UIImage`(`NSImage` on macOS) for rendering. For `SDAnimatedImageView`, it will use `SDAnimatedImage` for rendering.
@note The recommended approach for animated GIFs is using `SDAnimatedImage` with `SDAnimatedImageView`. It's more performant than `UIImageView` for GIF displaying(especially on memory usage)
*/
@interface SDImageGIFCoder : SDImageIOAnimatedCoder <SDProgressiveImageCoder, SDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) SDImageGIFCoder *sharedCoder;
@end

View File

@@ -0,0 +1,58 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageGIFCoder.h"
#import "SDImageIOAnimatedCoderInternal.h"
#if SD_MAC
#import <CoreServices/CoreServices.h>
#else
#import <MobileCoreServices/MobileCoreServices.h>
#endif
@implementation SDImageGIFCoder
+ (instancetype)sharedCoder {
static SDImageGIFCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageGIFCoder alloc] init];
});
return coder;
}
#pragma mark - Subclass Override
+ (SDImageFormat)imageFormat {
return SDImageFormatGIF;
}
+ (NSString *)imageUTType {
return (__bridge NSString *)kSDUTTypeGIF;
}
+ (NSString *)dictionaryProperty {
return (__bridge NSString *)kCGImagePropertyGIFDictionary;
}
+ (NSString *)unclampedDelayTimeProperty {
return (__bridge NSString *)kCGImagePropertyGIFUnclampedDelayTime;
}
+ (NSString *)delayTimeProperty {
return (__bridge NSString *)kCGImagePropertyGIFDelayTime;
}
+ (NSString *)loopCountProperty {
return (__bridge NSString *)kCGImagePropertyGIFLoopCount;
}
+ (NSUInteger)defaultLoopCount {
return 1;
}
@end

View File

@@ -0,0 +1,28 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import <CoreGraphics/CoreGraphics.h>
/**
These following graphics context method are provided to easily write cross-platform(AppKit/UIKit) code.
For UIKit, these methods just call the same method in `UIGraphics.h`. See the documentation for usage.
For AppKit, these methods use `NSGraphicsContext` to create image context and match the behavior like UIKit.
@note If you don't care bitmap format (ARGB8888) and just draw image, use `SDGraphicsImageRenderer` instead. It's more performant on RAM usage.`
*/
/// Returns the current graphics context.
FOUNDATION_EXPORT CGContextRef __nullable SDGraphicsGetCurrentContext(void) CF_RETURNS_NOT_RETAINED;
/// Creates a bitmap-based graphics context and makes it the current context.
FOUNDATION_EXPORT void SDGraphicsBeginImageContext(CGSize size);
/// Creates a bitmap-based graphics context with the specified options.
FOUNDATION_EXPORT void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
/// Removes the current bitmap-based graphics context from the top of the stack.
FOUNDATION_EXPORT void SDGraphicsEndImageContext(void);
/// Returns an image based on the contents of the current bitmap-based graphics context.
FOUNDATION_EXPORT UIImage * __nullable SDGraphicsGetImageFromCurrentImageContext(void);

View File

@@ -0,0 +1,126 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageGraphics.h"
#import "NSImage+Compatibility.h"
#import "SDImageCoderHelper.h"
#import "objc/runtime.h"
#if SD_MAC
static void *kNSGraphicsContextScaleFactorKey;
static CGContextRef SDCGContextCreateBitmapContext(CGSize size, BOOL opaque, CGFloat scale) {
if (scale == 0) {
// Match `UIGraphicsBeginImageContextWithOptions`, reset to the scale factor of the devices main screen if scale is 0.
NSScreen *mainScreen = nil;
if (@available(macOS 10.12, *)) {
mainScreen = [NSScreen mainScreen];
} else {
mainScreen = [NSScreen screens].firstObject;
}
scale = mainScreen.backingScaleFactor ?: 1.0f;
}
size_t width = ceil(size.width * scale);
size_t height = ceil(size.height * scale);
if (width < 1 || height < 1) return NULL;
CGColorSpaceRef space = [SDImageCoderHelper colorSpaceGetDeviceRGB];
// kCGImageAlphaNone is not supported in CGBitmapContextCreate.
// Check #3330 for more detail about why this bitmap is choosen.
// From v5.17.0, use runtime detection of bitmap info instead of hardcode.
// However, macOS's runtime detection will also call this function, cause recursive, so still hardcode here
CGBitmapInfo bitmapInfo;
if (!opaque) {
// [NSImage imageWithSize:flipped:drawingHandler:] returns float(16-bits) RGBA8888 on alpha image, which we don't need
bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
} else {
bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast;
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, bitmapInfo);
if (!context) {
return NULL;
}
CGContextScaleCTM(context, scale, scale);
return context;
}
#endif
CGContextRef SDGraphicsGetCurrentContext(void) {
#if SD_UIKIT || SD_WATCH
return UIGraphicsGetCurrentContext();
#else
return NSGraphicsContext.currentContext.CGContext;
#endif
}
void SDGraphicsBeginImageContext(CGSize size) {
#if SD_UIKIT || SD_WATCH
UIGraphicsBeginImageContext(size);
#else
SDGraphicsBeginImageContextWithOptions(size, NO, 1.0);
#endif
}
void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) {
#if SD_UIKIT || SD_WATCH
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
#else
CGContextRef context = SDCGContextCreateBitmapContext(size, opaque, scale);
if (!context) {
return;
}
NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithCGContext:context flipped:NO];
objc_setAssociatedObject(graphicsContext, &kNSGraphicsContextScaleFactorKey, @(scale), OBJC_ASSOCIATION_RETAIN);
CGContextRelease(context);
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext.currentContext = graphicsContext;
#endif
}
void SDGraphicsEndImageContext(void) {
#if SD_UIKIT || SD_WATCH
UIGraphicsEndImageContext();
#else
[NSGraphicsContext restoreGraphicsState];
#endif
}
UIImage * SDGraphicsGetImageFromCurrentImageContext(void) {
#if SD_UIKIT || SD_WATCH
return UIGraphicsGetImageFromCurrentImageContext();
#else
NSGraphicsContext *context = NSGraphicsContext.currentContext;
CGContextRef contextRef = context.CGContext;
if (!contextRef) {
return nil;
}
CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
if (!imageRef) {
return nil;
}
CGFloat scale = 0;
NSNumber *scaleFactor = objc_getAssociatedObject(context, &kNSGraphicsContextScaleFactorKey);
if ([scaleFactor isKindOfClass:[NSNumber class]]) {
scale = scaleFactor.doubleValue;
}
if (!scale) {
// reset to the scale factor of the devices main screen if scale is 0.
NSScreen *mainScreen = nil;
if (@available(macOS 10.12, *)) {
mainScreen = [NSScreen mainScreen];
} else {
mainScreen = [NSScreen screens].firstObject;
}
scale = mainScreen.backingScaleFactor ?: 1.0f;
}
NSImage *image = [[NSImage alloc] initWithCGImage:imageRef scale:scale orientation:kCGImagePropertyOrientationUp];
CGImageRelease(imageRef);
return image;
#endif
}

View File

@@ -0,0 +1,25 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageIOAnimatedCoder.h"
/**
This coder is used for HEIC (HEIF with HEVC container codec) image format.
Image/IO provide the static HEIC (.heic) support in iOS 11/macOS 10.13/tvOS 11/watchOS 4+.
Image/IO provide the animated HEIC (.heics) support in iOS 13/macOS 10.15/tvOS 13/watchOS 6+.
See https://nokiatech.github.io/heif/technical.html for the standard.
@note This coder is not in the default coder list for now, since HEIC animated image is really rare, and Apple's implementation still contains performance issues. You can enable if you need this.
@note If you need to support lower firmware version for HEIF, you can have a try at https://github.com/SDWebImage/SDWebImageHEIFCoder
*/
API_AVAILABLE(ios(13.0), tvos(13.0), macos(10.15), watchos(6.0))
@interface SDImageHEICCoder : SDImageIOAnimatedCoder <SDProgressiveImageCoder, SDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) SDImageHEICCoder *sharedCoder;
@end

View File

@@ -0,0 +1,109 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageHEICCoder.h"
#import "SDImageIOAnimatedCoderInternal.h"
// These constants are available from iOS 13+ and Xcode 11. This raw value is used for toolchain and firmware compatibility
static NSString * kSDCGImagePropertyHEICSDictionary = @"{HEICS}";
static NSString * kSDCGImagePropertyHEICSLoopCount = @"LoopCount";
static NSString * kSDCGImagePropertyHEICSDelayTime = @"DelayTime";
static NSString * kSDCGImagePropertyHEICSUnclampedDelayTime = @"UnclampedDelayTime";
@implementation SDImageHEICCoder
+ (void)initialize {
if (@available(iOS 13, tvOS 13, macOS 10.15, watchOS 6, *)) {
// Use SDK instead of raw value
kSDCGImagePropertyHEICSDictionary = (__bridge NSString *)kCGImagePropertyHEICSDictionary;
kSDCGImagePropertyHEICSLoopCount = (__bridge NSString *)kCGImagePropertyHEICSLoopCount;
kSDCGImagePropertyHEICSDelayTime = (__bridge NSString *)kCGImagePropertyHEICSDelayTime;
kSDCGImagePropertyHEICSUnclampedDelayTime = (__bridge NSString *)kCGImagePropertyHEICSUnclampedDelayTime;
}
}
+ (instancetype)sharedCoder {
static SDImageHEICCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageHEICCoder alloc] init];
});
return coder;
}
#pragma mark - SDImageCoder
- (BOOL)canDecodeFromData:(nullable NSData *)data {
switch ([NSData sd_imageFormatForImageData:data]) {
case SDImageFormatHEIC:
// Check HEIC decoding compatibility
return [self.class canDecodeFromFormat:SDImageFormatHEIC];
case SDImageFormatHEIF:
// Check HEIF decoding compatibility
return [self.class canDecodeFromFormat:SDImageFormatHEIF];
default:
return NO;
}
}
- (BOOL)canIncrementalDecodeFromData:(NSData *)data {
return [self canDecodeFromData:data];
}
- (BOOL)canEncodeToFormat:(SDImageFormat)format {
switch (format) {
case SDImageFormatHEIC:
// Check HEIC encoding compatibility
return [self.class canEncodeToFormat:SDImageFormatHEIC];
case SDImageFormatHEIF:
// Check HEIF encoding compatibility
return [self.class canEncodeToFormat:SDImageFormatHEIF];
default:
return NO;
}
}
#pragma mark - Subclass Override
+ (SDImageFormat)imageFormat {
return SDImageFormatHEIC;
}
+ (NSString *)imageUTType {
// See: https://nokiatech.github.io/heif/technical.html
// Actually HEIC has another concept called `non-timed Image Sequence`, which can be encoded using `public.heic`
return (__bridge NSString *)kSDUTTypeHEIC;
}
+ (NSString *)animatedImageUTType {
// See: https://nokiatech.github.io/heif/technical.html
// We use `timed Image Sequence`, means, `public.heics` for animated image encoding
return (__bridge NSString *)kSDUTTypeHEICS;
}
+ (NSString *)dictionaryProperty {
return kSDCGImagePropertyHEICSDictionary;
}
+ (NSString *)unclampedDelayTimeProperty {
return kSDCGImagePropertyHEICSUnclampedDelayTime;
}
+ (NSString *)delayTimeProperty {
return kSDCGImagePropertyHEICSDelayTime;
}
+ (NSString *)loopCountProperty {
return kSDCGImagePropertyHEICSLoopCount;
}
+ (NSUInteger)defaultLoopCount {
return 0;
}
@end

View File

@@ -0,0 +1,65 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageCoder.h"
/**
This is the abstract class for all animated coder, which use the Image/IO API. You can not use this directly as real coders. A exception will be raised if you use this class.
All of the properties need the subclass to implement and works as expected.
For Image/IO, See Apple's documentation: https://developer.apple.com/documentation/imageio
*/
@interface SDImageIOAnimatedCoder : NSObject <SDProgressiveImageCoder, SDAnimatedImageCoder>
#pragma mark - Subclass Override
/**
The supported animated image format. Such as `SDImageFormatGIF`.
@note Subclass override.
*/
@property (class, readonly) SDImageFormat imageFormat;
/**
The supported image format UTI Type. Such as `kSDUTTypeGIF`.
This can be used for cases when we can not detect `SDImageFormat. Such as progressive decoding's hint format `kCGImageSourceTypeIdentifierHint`.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *imageUTType;
/**
Some image codec use different UTI Type between animated image and static image.
For this case, override this method and return the UTI for animated image encoding.
@note Defaults to use the value of `imageUTType`, so it's @optional actually.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *animatedImageUTType;
/**
The image container property key used in Image/IO API. Such as `kCGImagePropertyGIFDictionary`.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *dictionaryProperty;
/**
The image unclamped delay time property key used in Image/IO API. Such as `kCGImagePropertyGIFUnclampedDelayTime`
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *unclampedDelayTimeProperty;
/**
The image delay time property key used in Image/IO API. Such as `kCGImagePropertyGIFDelayTime`.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *delayTimeProperty;
/**
The image loop count property key used in Image/IO API. Such as `kCGImagePropertyGIFLoopCount`.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *loopCountProperty;
/**
The default loop count when there are no any loop count information inside image container metadata.
For example, for GIF format, the standard use 1 (play once). For APNG format, the standard use 0 (infinity loop).
@note Subclass override.
*/
@property (class, readonly) NSUInteger defaultLoopCount;
@end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDImageCoder.h"
/**
Built in coder that supports PNG, JPEG, TIFF, includes support for progressive decoding.
GIF
Also supports static GIF (meaning will only handle the 1st frame).
For a full GIF support, we recommend `SDAnimatedImageView` to keep both CPU and memory balanced.
HEIC
This coder also supports HEIC format because ImageIO supports it natively. But it depends on the system capabilities, so it won't work on all devices, see: https://devstreaming-cdn.apple.com/videos/wwdc/2017/511tj33587vdhds/511/511_working_with_heif_and_hevc.pdf
Decode(Software): !Simulator && (iOS 11 || tvOS 11 || macOS 10.13)
Decode(Hardware): !Simulator && ((iOS 11 && A9Chip) || (macOS 10.13 && 6thGenerationIntelCPU))
Encode(Software): macOS 10.13
Encode(Hardware): !Simulator && ((iOS 11 && A10FusionChip) || (macOS 10.13 && 6thGenerationIntelCPU))
*/
@interface SDImageIOCoder : NSObject <SDProgressiveImageCoder>
@property (nonatomic, class, readonly, nonnull) SDImageIOCoder *sharedCoder;
@end

View File

@@ -0,0 +1,458 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageIOCoder.h"
#import "SDImageCoderHelper.h"
#import "NSImage+Compatibility.h"
#import "UIImage+Metadata.h"
#import "SDImageGraphics.h"
#import "SDImageIOAnimatedCoderInternal.h"
#import <ImageIO/ImageIO.h>
#import <CoreServices/CoreServices.h>
// Specify File Size for lossy format encoding, like JPEG
static NSString * kSDCGImageDestinationRequestedFileSize = @"kCGImageDestinationRequestedFileSize";
// Support Xcode 15 SDK, use raw value instead of symbol
static NSString * kSDCGImageDestinationEncodeRequest = @"kCGImageDestinationEncodeRequest";
static NSString * kSDCGImageDestinationEncodeToSDR = @"kCGImageDestinationEncodeToSDR";
static NSString * kSDCGImageDestinationEncodeToISOHDR = @"kCGImageDestinationEncodeToISOHDR";
static NSString * kSDCGImageDestinationEncodeToISOGainmap = @"kCGImageDestinationEncodeToISOGainmap";
@implementation SDImageIOCoder {
size_t _width, _height;
CGImagePropertyOrientation _orientation;
CGImageSourceRef _imageSource;
CGFloat _scale;
BOOL _finished;
BOOL _preserveAspectRatio;
CGSize _thumbnailSize;
BOOL _lazyDecode;
BOOL _decodeToHDR;
}
#if SD_IMAGEIO_HDR_ENCODING
+ (void)initialize {
if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) {
// Use SDK instead of raw value
kSDCGImageDestinationEncodeRequest = (__bridge NSString *)kCGImageDestinationEncodeRequest;
kSDCGImageDestinationEncodeToSDR = (__bridge NSString *)kCGImageDestinationEncodeToSDR;
kSDCGImageDestinationEncodeToISOHDR = (__bridge NSString *)kCGImageDestinationEncodeToISOHDR;
kSDCGImageDestinationEncodeToISOGainmap = (__bridge NSString *)kCGImageDestinationEncodeToISOGainmap;
}
}
#endif
- (void)dealloc {
if (_imageSource) {
CFRelease(_imageSource);
_imageSource = NULL;
}
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
- (void)didReceiveMemoryWarning:(NSNotification *)notification
{
if (_imageSource) {
CGImageSourceRemoveCacheAtIndex(_imageSource, 0);
}
}
+ (instancetype)sharedCoder {
static SDImageIOCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageIOCoder alloc] init];
});
return coder;
}
#pragma mark - Bitmap PDF representation
+ (UIImage *)createBitmapPDFWithData:(nonnull NSData *)data pageNumber:(NSUInteger)pageNumber targetSize:(CGSize)targetSize preserveAspectRatio:(BOOL)preserveAspectRatio {
NSParameterAssert(data);
UIImage *image;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if (!provider) {
return nil;
}
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
if (!document) {
return nil;
}
// `CGPDFDocumentGetPage` page number is 1-indexed.
CGPDFPageRef page = CGPDFDocumentGetPage(document, pageNumber + 1);
if (!page) {
CGPDFDocumentRelease(document);
return nil;
}
CGPDFBox box = kCGPDFMediaBox;
CGRect rect = CGPDFPageGetBoxRect(page, box);
CGRect targetRect = rect;
if (!CGSizeEqualToSize(targetSize, CGSizeZero)) {
targetRect = CGRectMake(0, 0, targetSize.width, targetSize.height);
}
CGFloat xRatio = targetRect.size.width / rect.size.width;
CGFloat yRatio = targetRect.size.height / rect.size.height;
CGFloat xScale = preserveAspectRatio ? MIN(xRatio, yRatio) : xRatio;
CGFloat yScale = preserveAspectRatio ? MIN(xRatio, yRatio) : yRatio;
// `CGPDFPageGetDrawingTransform` will only scale down, but not scale up, so we need calculate the actual scale again
CGRect drawRect = CGRectMake( 0, 0, targetRect.size.width / xScale, targetRect.size.height / yScale);
CGAffineTransform scaleTransform = CGAffineTransformMakeScale(xScale, yScale);
CGAffineTransform transform = CGPDFPageGetDrawingTransform(page, box, drawRect, 0, preserveAspectRatio);
SDGraphicsBeginImageContextWithOptions(targetRect.size, NO, 0);
CGContextRef context = SDGraphicsGetCurrentContext();
#if SD_UIKIT || SD_WATCH
// Core Graphics coordinate system use the bottom-left, UIKit use the flipped one
CGContextTranslateCTM(context, 0, targetRect.size.height);
CGContextScaleCTM(context, 1, -1);
#endif
CGContextConcatCTM(context, scaleTransform);
CGContextConcatCTM(context, transform);
CGContextDrawPDFPage(context, page);
image = SDGraphicsGetImageFromCurrentImageContext();
SDGraphicsEndImageContext();
CGPDFDocumentRelease(document);
return image;
}
#pragma mark - Decode
- (BOOL)canDecodeFromData:(nullable NSData *)data {
return YES;
}
- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options {
if (!data) {
return nil;
}
CGFloat scale = 1;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = MAX([scaleFactor doubleValue], 1) ;
}
CGSize thumbnailSize = CGSizeZero;
NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize];
if (thumbnailSizeValue != nil) {
#if SD_MAC
thumbnailSize = thumbnailSizeValue.sizeValue;
#else
thumbnailSize = thumbnailSizeValue.CGSizeValue;
#endif
}
BOOL preserveAspectRatio = YES;
NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio];
if (preserveAspectRatioValue != nil) {
preserveAspectRatio = preserveAspectRatioValue.boolValue;
}
// Check vector format
if ([NSData sd_imageFormatForImageData:data] == SDImageFormatPDF) {
// History before iOS 16, ImageIO can decode PDF with rasterization size, but can't ever :(
// So, use CoreGraphics to decode PDF (copy code from SDWebImagePDFCoder, may do refactor in the future)
UIImage *image;
NSUInteger pageNumber = 0; // Still use first page, may added options is user want
#if SD_MAC
// If don't use thumbnail, prefers the built-in generation of vector image
// macOS's `NSImage` supports PDF built-in rendering
if (thumbnailSize.width == 0 || thumbnailSize.height == 0) {
NSPDFImageRep *imageRep = [[NSPDFImageRep alloc] initWithData:data];
if (imageRep) {
imageRep.currentPage = pageNumber;
image = [[NSImage alloc] initWithSize:imageRep.size];
[image addRepresentation:imageRep];
image.sd_imageFormat = SDImageFormatPDF;
return image;
}
}
#endif
image = [self.class createBitmapPDFWithData:data pageNumber:pageNumber targetSize:thumbnailSize preserveAspectRatio:preserveAspectRatio];
image.sd_imageFormat = SDImageFormatPDF;
return image;
}
BOOL lazyDecode = YES; // Defaults YES for static image coder
NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding];
if (lazyDecodeValue != nil) {
lazyDecode = lazyDecodeValue.boolValue;
}
BOOL decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue];
NSString *typeIdentifierHint = options[SDImageCoderDecodeTypeIdentifierHint];
if (!typeIdentifierHint) {
// Check file extension and convert to UTI, from: https://stackoverflow.com/questions/1506251/getting-an-uniform-type-identifier-for-a-given-extension
NSString *fileExtensionHint = options[SDImageCoderDecodeFileExtensionHint];
if (fileExtensionHint) {
typeIdentifierHint = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtensionHint, kUTTypeImage);
// Ignore dynamic UTI
if (UTTypeIsDynamic((__bridge CFStringRef)typeIdentifierHint)) {
typeIdentifierHint = nil;
}
}
} else if ([typeIdentifierHint isEqual:NSNull.null]) {
// Hack if user don't want to imply file extension
typeIdentifierHint = nil;
}
NSDictionary *creatingOptions = nil;
if (typeIdentifierHint) {
creatingOptions = @{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : typeIdentifierHint};
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)creatingOptions);
if (!source) {
// Try again without UTType hint, the call site from user may provide the wrong UTType
source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil);
}
if (!source) {
return nil;
}
CFStringRef uttype = CGImageSourceGetType(source);
SDImageFormat imageFormat = [NSData sd_imageFormatFromUTType:uttype];
UIImage *image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize lazyDecode:lazyDecode animatedImage:NO decodeToHDR:decodeToHDR];
CFRelease(source);
image.sd_imageFormat = imageFormat;
return image;
}
#pragma mark - Progressive Decode
- (BOOL)canIncrementalDecodeFromData:(NSData *)data {
return [self canDecodeFromData:data];
}
- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options {
self = [super init];
if (self) {
_imageSource = CGImageSourceCreateIncremental(NULL);
CGFloat scale = 1;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = MAX([scaleFactor doubleValue], 1);
}
_scale = scale;
CGSize thumbnailSize = CGSizeZero;
NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize];
if (thumbnailSizeValue != nil) {
#if SD_MAC
thumbnailSize = thumbnailSizeValue.sizeValue;
#else
thumbnailSize = thumbnailSizeValue.CGSizeValue;
#endif
}
_thumbnailSize = thumbnailSize;
BOOL preserveAspectRatio = YES;
NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio];
if (preserveAspectRatioValue != nil) {
preserveAspectRatio = preserveAspectRatioValue.boolValue;
}
_preserveAspectRatio = preserveAspectRatio;
BOOL lazyDecode = YES; // Defaults YES for static image coder
NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding];
if (lazyDecodeValue != nil) {
lazyDecode = lazyDecodeValue.boolValue;
}
_lazyDecode = lazyDecode;
_decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue];
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
return self;
}
- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished {
if (_finished) {
return;
}
_finished = finished;
// The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
// Thanks to the author @Nyx0uf
// Update the data source, we must pass ALL the data, not just the new bytes
CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished);
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 didCompleteWithError.) So save it here and pass it on later.
_orientation = (CGImagePropertyOrientation)orientationValue;
}
}
}
- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options {
UIImage *image;
if (_width + _height > 0) {
// Create the image
CGFloat scale = _scale;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = MAX([scaleFactor doubleValue], 1);
}
image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:_imageSource scale:scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize lazyDecode:_lazyDecode animatedImage:NO decodeToHDR:_finished ? _decodeToHDR : NO];
if (image) {
CFStringRef uttype = CGImageSourceGetType(_imageSource);
image.sd_imageFormat = [NSData sd_imageFormatFromUTType:uttype];
}
}
return image;
}
#pragma mark - Encode
- (BOOL)canEncodeToFormat:(SDImageFormat)format {
return YES;
}
- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options {
if (!image) {
return nil;
}
CGImageRef imageRef = image.CGImage;
if (!imageRef) {
// Earily return, supports CGImage only
return nil;
}
if (format == SDImageFormatUndefined) {
BOOL hasAlpha = [SDImageCoderHelper CGImageContainsAlpha:imageRef];
if (hasAlpha) {
format = SDImageFormatPNG;
} else {
format = SDImageFormatJPEG;
}
}
NSMutableData *imageData = [NSMutableData data];
CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
if (!imageDestination) {
// Handle failure.
return nil;
}
NSMutableDictionary *properties = [NSMutableDictionary dictionary];
#if SD_UIKIT || SD_WATCH
CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation];
#else
CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp;
#endif
properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation);
// Encoding Options
double compressionQuality = 1;
if (options[SDImageCoderEncodeCompressionQuality]) {
compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue];
}
properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality);
CGColorRef backgroundColor = [options[SDImageCoderEncodeBackgroundColor] CGColor];
if (backgroundColor) {
properties[(__bridge NSString *)kCGImageDestinationBackgroundColor] = (__bridge id)(backgroundColor);
}
CGSize maxPixelSize = CGSizeZero;
NSValue *maxPixelSizeValue = options[SDImageCoderEncodeMaxPixelSize];
if (maxPixelSizeValue != nil) {
#if SD_MAC
maxPixelSize = maxPixelSizeValue.sizeValue;
#else
maxPixelSize = maxPixelSizeValue.CGSizeValue;
#endif
}
// HDR Encoding
NSUInteger encodeToHDR = 0;
if (options[SDImageCoderEncodeToHDR]) {
encodeToHDR = [options[SDImageCoderEncodeToHDR] unsignedIntegerValue];
}
if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) {
if (encodeToHDR == SDImageHDRTypeISOHDR) {
properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOHDR;
} else if (encodeToHDR == SDImageHDRTypeISOGainMap) {
properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOGainmap;
} else {
properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToSDR;
}
}
CGFloat pixelWidth = (CGFloat)CGImageGetWidth(imageRef);
CGFloat pixelHeight = (CGFloat)CGImageGetHeight(imageRef);
CGFloat finalPixelSize = 0;
BOOL encodeFullImage = maxPixelSize.width == 0 || maxPixelSize.height == 0 || pixelWidth == 0 || pixelHeight == 0 || (pixelWidth <= maxPixelSize.width && pixelHeight <= maxPixelSize.height);
if (!encodeFullImage) {
// Thumbnail Encoding
CGFloat pixelRatio = pixelWidth / pixelHeight;
CGFloat maxPixelSizeRatio = maxPixelSize.width / maxPixelSize.height;
if (pixelRatio > maxPixelSizeRatio) {
finalPixelSize = MAX(maxPixelSize.width, maxPixelSize.width / pixelRatio);
} else {
finalPixelSize = MAX(maxPixelSize.height, maxPixelSize.height * pixelRatio);
}
properties[(__bridge NSString *)kCGImageDestinationImageMaxPixelSize] = @(finalPixelSize);
}
NSUInteger maxFileSize = [options[SDImageCoderEncodeMaxFileSize] unsignedIntegerValue];
if (maxFileSize > 0) {
properties[kSDCGImageDestinationRequestedFileSize] = @(maxFileSize);
// Remove the quality if we have file size limit
properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = nil;
}
BOOL embedThumbnail = NO;
if (options[SDImageCoderEncodeEmbedThumbnail]) {
embedThumbnail = [options[SDImageCoderEncodeEmbedThumbnail] boolValue];
}
properties[(__bridge NSString *)kCGImageDestinationEmbedThumbnail] = @(embedThumbnail);
// Add your image to the destination.
CGImageDestinationAddImage(imageDestination, imageRef, (__bridge CFDictionaryRef)properties);
// Finalize the destination.
if (CGImageDestinationFinalize(imageDestination) == NO) {
// Handle failure.
imageData = nil;
}
CFRelease(imageDestination);
return [imageData copy];
}
@end

View File

@@ -0,0 +1,146 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "SDWebImageDefine.h"
#import "SDWebImageOperation.h"
#import "SDImageCoder.h"
typedef void(^SDImageLoaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL);
typedef void(^SDImageLoaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished);
#pragma mark - Context Options
/**
A `UIImage` instance from `SDWebImageManager` when you specify `SDWebImageRefreshCached` and image cache hit.
This can be a hint for image loader to load the image from network and refresh the image from remote location if needed. If the image from remote location does not change, you should call the completion with `SDWebImageErrorCacheNotModified` error. (UIImage)
@note If you don't implement `SDWebImageRefreshCached` support, you do not need to care about this context option.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextLoaderCachedImage;
#pragma mark - Helper method
/**
This is the built-in decoding process for image download from network or local file.
@note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image.
@param imageData The image data from the network. Should not be nil
@param imageURL The image URL from the input. Should not be nil
@param options The options arg from the input
@param context The context arg from the input
@return The decoded image for current image data load from the network
*/
FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context);
/**
This is the built-in decoding process for image progressive download from network. It's used when `SDWebImageProgressiveLoad` option is set. (It's not required when your loader does not support progressive image loading)
@note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image.
@param imageData The image data from the network so far. Should not be nil
@param imageURL The image URL from the input. Should not be nil
@param finished Pass NO to specify the download process has not finished. Pass YES when all image data has finished.
@param operation The loader operation associated with current progressive download. Why to provide this is because progressive decoding need to store the partial decoded context for each operation to avoid conflict. You should provide the operation from `loadImageWithURL:` method return value.
@param options The options arg from the input
@param context The context arg from the input
@return The decoded progressive image for current image data load from the network
*/
FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id<SDWebImageOperation> _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context);
/**
This function get the progressive decoder for current loading operation. If no progressive decoding is happended or decoder is not able to construct, return nil.
@return The progressive decoder associated with the loading operation.
*/
FOUNDATION_EXPORT id<SDProgressiveImageCoder> _Nullable SDImageLoaderGetProgressiveCoder(id<SDWebImageOperation> _Nonnull operation);
/**
This function set the progressive decoder for current loading operation. If no progressive decoding is happended, pass nil.
@param progressiveCoder The loading operation to associate the progerssive decoder.
*/
FOUNDATION_EXPORT void SDImageLoaderSetProgressiveCoder(id<SDWebImageOperation> _Nonnull operation, id<SDProgressiveImageCoder> _Nullable progressiveCoder);
#pragma mark - SDImageLoader
/**
This is the protocol to specify custom image load process. You can create your own class to conform this protocol and use as a image loader to load image from network or any available remote resources defined by yourself.
If you want to implement custom loader for image download from network or local file, you just need to concentrate on image data download only. After the download finish, call `SDImageLoaderDecodeImageData` or `SDImageLoaderDecodeProgressiveImageData` to use the built-in decoding process and produce image (Remember to call in the global queue). And finally callback the completion block.
If you directly get the image instance using some third-party SDKs, such as image directly from Photos framework. You can process the image data and image instance by yourself without that built-in decoding process. And finally callback the completion block.
@note It's your responsibility to load the image in the desired global queue(to avoid block main queue). We do not dispatch these method call in a global queue but just from the call queue (For `SDWebImageManager`, it typically call from the main queue).
*/
@protocol SDImageLoader <NSObject>
@required
/**
Whether current image loader supports to load the provide image URL.
This will be checked every time a new image request come for loader. If this return NO, we will mark this image load as failed. If return YES, we will start to call `requestImageWithURL:options:context:progress:completed:`.
@param url The image URL to be loaded.
@return YES to continue download, NO to stop download.
*/
- (BOOL)canRequestImageForURL:(nullable NSURL *)url API_DEPRECATED_WITH_REPLACEMENT("canRequestImageForURL:options:context:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@optional
/**
Whether current image loader supports to load the provide image URL, with associated options and context.
This will be checked every time a new image request come for loader. If this return NO, we will mark this image load as failed. If return YES, we will start to call `requestImageWithURL:options:context:progress:completed:`.
@param url The image URL to be loaded.
@param options A mask to specify options to use for this request
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@return YES to continue download, NO to stop download.
*/
- (BOOL)canRequestImageForURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
@required
/**
Load the image and image data with the given URL and return the image data. You're responsible for producing the image instance.
@param url The URL represent the image. Note this may not be a HTTP URL
@param options A mask to specify options to use for this request
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
@param completedBlock A block called when operation has been completed.
@return An operation which allow the user to cancel the current request.
*/
- (nullable id<SDWebImageOperation>)requestImageWithURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDImageLoaderCompletedBlock)completedBlock;
/**
Whether the error from image loader should be marked indeed un-recoverable or not.
If this return YES, failed URL which does not using `SDWebImageRetryFailed` will be blocked into black list. Else not.
@param url The URL represent the image. Note this may not be a HTTP URL
@param error The URL's loading error, from previous `requestImageWithURL:options:context:progress:completed:` completedBlock's error.
@return Whether to block this url or not. Return YES to mark this URL as failed.
*/
- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url
error:(nonnull NSError *)error API_DEPRECATED_WITH_REPLACEMENT("shouldBlockFailedURLWithURL:error:options:context:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@optional
/**
Whether the error from image loader should be marked indeed un-recoverable or not, with associated options and context.
If this return YES, failed URL which does not using `SDWebImageRetryFailed` will be blocked into black list. Else not.
@param url The URL represent the image. Note this may not be a HTTP URL
@param error The URL's loading error, from previous `requestImageWithURL:options:context:progress:completed:` completedBlock's error.
@param options A mask to specify options to use for this request
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@return Whether to block this url or not. Return YES to mark this URL as failed.
*/
- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url
error:(nonnull NSError *)error
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
@end

View File

@@ -0,0 +1,178 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageLoader.h"
#import "SDWebImageCacheKeyFilter.h"
#import "SDImageCodersManager.h"
#import "SDImageCoderHelper.h"
#import "SDAnimatedImage.h"
#import "UIImage+Metadata.h"
#import "SDInternalMacros.h"
#import "SDImageCacheDefine.h"
#import "objc/runtime.h"
SDWebImageContextOption const SDWebImageContextLoaderCachedImage = @"loaderCachedImage";
static void * SDImageLoaderProgressiveCoderKey = &SDImageLoaderProgressiveCoderKey;
id<SDProgressiveImageCoder> SDImageLoaderGetProgressiveCoder(id<SDWebImageOperation> operation) {
NSCParameterAssert(operation);
return objc_getAssociatedObject(operation, SDImageLoaderProgressiveCoderKey);
}
void SDImageLoaderSetProgressiveCoder(id<SDWebImageOperation> operation, id<SDProgressiveImageCoder> progressiveCoder) {
NSCParameterAssert(operation);
objc_setAssociatedObject(operation, SDImageLoaderProgressiveCoderKey, progressiveCoder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
NSCParameterAssert(imageData);
NSCParameterAssert(imageURL);
UIImage *image;
id<SDWebImageCacheKeyFilter> cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
NSString *cacheKey;
if (cacheKeyFilter) {
cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL];
} else {
cacheKey = imageURL.absoluteString;
}
SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey);
BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue];
// Grab the image coder
id<SDImageCoder> imageCoder = context[SDWebImageContextImageCoder];
if (!imageCoder) {
imageCoder = [SDImageCodersManager sharedManager];
}
if (!decodeFirstFrame) {
// check whether we should use `SDAnimatedImage`
Class animatedImageClass = context[SDWebImageContextAnimatedImageClass];
if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) {
image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions];
if (image) {
// Preload frames if supported
if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) {
[((id<SDAnimatedImage>)image) preloadAllFrames];
}
} else {
// Check image class matching
if (options & SDWebImageMatchAnimatedImageClass) {
return nil;
}
}
}
}
if (!image) {
image = [imageCoder decodedImageWithData:imageData options:coderOptions];
}
if (image) {
SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic;
NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy];
if (policyValue != nil) {
policy = policyValue.unsignedIntegerValue;
}
// TODO: Deprecated, remove in SD 6.0...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) {
policy = SDImageForceDecodePolicyNever;
}
#pragma clang diagnostic pop
image = [SDImageCoderHelper decodedImageWithImage:image policy:policy];
// assign the decode options, to let manager check whether to re-decode if needed
image.sd_decodeOptions = coderOptions;
}
return image;
}
UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id<SDWebImageOperation> _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
NSCParameterAssert(imageData);
NSCParameterAssert(imageURL);
NSCParameterAssert(operation);
UIImage *image;
id<SDWebImageCacheKeyFilter> cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
NSString *cacheKey;
if (cacheKeyFilter) {
cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL];
} else {
cacheKey = imageURL.absoluteString;
}
SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey);
BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue];
// Grab the progressive image coder
id<SDProgressiveImageCoder> progressiveCoder = SDImageLoaderGetProgressiveCoder(operation);
if (!progressiveCoder) {
id<SDProgressiveImageCoder> imageCoder = context[SDWebImageContextImageCoder];
// Check the progressive coder if provided
if ([imageCoder respondsToSelector:@selector(initIncrementalWithOptions:)]) {
progressiveCoder = [[[imageCoder class] alloc] initIncrementalWithOptions:coderOptions];
} else {
// We need to create a new instance for progressive decoding to avoid conflicts
for (id<SDImageCoder> coder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) {
if ([coder conformsToProtocol:@protocol(SDProgressiveImageCoder)] &&
[((id<SDProgressiveImageCoder>)coder) canIncrementalDecodeFromData:imageData]) {
progressiveCoder = [[[coder class] alloc] initIncrementalWithOptions:coderOptions];
break;
}
}
}
SDImageLoaderSetProgressiveCoder(operation, progressiveCoder);
}
// If we can't find any progressive coder, disable progressive download
if (!progressiveCoder) {
return nil;
}
[progressiveCoder updateIncrementalData:imageData finished:finished];
if (!decodeFirstFrame) {
// check whether we should use `SDAnimatedImage`
Class animatedImageClass = context[SDWebImageContextAnimatedImageClass];
if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)] && [progressiveCoder respondsToSelector:@selector(animatedImageFrameAtIndex:)]) {
image = [[animatedImageClass alloc] initWithAnimatedCoder:(id<SDAnimatedImageCoder>)progressiveCoder scale:scale];
if (image) {
// Progressive decoding does not preload frames
} else {
// Check image class matching
if (options & SDWebImageMatchAnimatedImageClass) {
return nil;
}
}
}
}
if (!image) {
image = [progressiveCoder incrementalDecodedImageWithOptions:coderOptions];
}
if (image) {
SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic;
NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy];
if (policyValue != nil) {
policy = policyValue.unsignedIntegerValue;
}
// TODO: Deprecated, remove in SD 6.0...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) {
policy = SDImageForceDecodePolicyNever;
}
#pragma clang diagnostic pop
image = [SDImageCoderHelper decodedImageWithImage:image policy:policy];
// assign the decode options, to let manager check whether to re-decode if needed
image.sd_decodeOptions = coderOptions;
// mark the image as progressive (completed one are not mark as progressive)
image.sd_isIncremental = !finished;
}
return image;
}

View File

@@ -0,0 +1,40 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageLoader.h"
/**
A loaders manager to manage multiple loaders
*/
@interface SDImageLoadersManager : NSObject <SDImageLoader>
/**
Returns the global shared loaders manager instance. By default we will set [`SDWebImageDownloader.sharedDownloader`] into the loaders array.
*/
@property (nonatomic, class, readonly, nonnull) SDImageLoadersManager *sharedManager;
/**
All image loaders in manager. The loaders array is a priority queue, which means the later added loader will have the highest priority
*/
@property (nonatomic, copy, nullable) NSArray<id<SDImageLoader>>* loaders;
/**
Add a new image loader to the end of loaders array. Which has the highest priority.
@param loader loader
*/
- (void)addLoader:(nonnull id<SDImageLoader>)loader;
/**
Remove an image loader in the loaders array.
@param loader loader
*/
- (void)removeLoader:(nonnull id<SDImageLoader>)loader;
@end

View File

@@ -0,0 +1,123 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageLoadersManager.h"
#import "SDWebImageDownloader.h"
#import "SDInternalMacros.h"
@interface SDImageLoadersManager ()
@property (nonatomic, strong, nonnull) NSMutableArray<id<SDImageLoader>> *imageLoaders;
@end
@implementation SDImageLoadersManager {
SD_LOCK_DECLARE(_loadersLock);
}
+ (SDImageLoadersManager *)sharedManager {
static dispatch_once_t onceToken;
static SDImageLoadersManager *manager;
dispatch_once(&onceToken, ^{
manager = [[SDImageLoadersManager alloc] init];
});
return manager;
}
- (instancetype)init {
self = [super init];
if (self) {
// initialize with default image loaders
_imageLoaders = [NSMutableArray arrayWithObject:[SDWebImageDownloader sharedDownloader]];
SD_LOCK_INIT(_loadersLock);
}
return self;
}
- (NSArray<id<SDImageLoader>> *)loaders {
SD_LOCK(_loadersLock);
NSArray<id<SDImageLoader>>* loaders = [_imageLoaders copy];
SD_UNLOCK(_loadersLock);
return loaders;
}
- (void)setLoaders:(NSArray<id<SDImageLoader>> *)loaders {
SD_LOCK(_loadersLock);
[_imageLoaders removeAllObjects];
if (loaders.count) {
[_imageLoaders addObjectsFromArray:loaders];
}
SD_UNLOCK(_loadersLock);
}
#pragma mark - Loader Property
- (void)addLoader:(id<SDImageLoader>)loader {
if (![loader conformsToProtocol:@protocol(SDImageLoader)]) {
return;
}
SD_LOCK(_loadersLock);
[_imageLoaders addObject:loader];
SD_UNLOCK(_loadersLock);
}
- (void)removeLoader:(id<SDImageLoader>)loader {
if (![loader conformsToProtocol:@protocol(SDImageLoader)]) {
return;
}
SD_LOCK(_loadersLock);
[_imageLoaders removeObject:loader];
SD_UNLOCK(_loadersLock);
}
#pragma mark - SDImageLoader
- (BOOL)canRequestImageForURL:(nullable NSURL *)url {
return [self canRequestImageForURL:url options:0 context:nil];
}
- (BOOL)canRequestImageForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
NSArray<id<SDImageLoader>> *loaders = self.loaders;
for (id<SDImageLoader> loader in loaders.reverseObjectEnumerator) {
if ([loader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) {
if ([loader canRequestImageForURL:url options:options context:context]) {
return YES;
}
} else {
if ([loader canRequestImageForURL:url]) {
return YES;
}
}
}
return NO;
}
- (id<SDWebImageOperation>)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock {
if (!url) {
return nil;
}
NSArray<id<SDImageLoader>> *loaders = self.loaders;
for (id<SDImageLoader> loader in loaders.reverseObjectEnumerator) {
if ([loader canRequestImageForURL:url]) {
return [loader requestImageWithURL:url options:options context:context progress:progressBlock completed:completedBlock];
}
}
return nil;
}
- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error {
NSArray<id<SDImageLoader>> *loaders = self.loaders;
for (id<SDImageLoader> loader in loaders.reverseObjectEnumerator) {
if ([loader canRequestImageForURL:url]) {
return [loader shouldBlockFailedURLWithURL:url error:error];
}
}
return NO;
}
@end

View File

@@ -0,0 +1,283 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "UIImage+Transform.h"
/**
Return the transformed cache key which applied with specify transformerKey.
@param key The original cache key
@param transformerKey The transformer key from the transformer
@return The transformed cache key
*/
FOUNDATION_EXPORT NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey);
/**
Return the thumbnailed cache key which applied with specify thumbnailSize and preserveAspectRatio control.
@param key The original cache key
@param thumbnailPixelSize The thumbnail pixel size
@param preserveAspectRatio The preserve aspect ratio option
@return The thumbnailed cache key
@note If you have both transformer and thumbnail applied for image, call `SDThumbnailedKeyForKey` firstly and then with `SDTransformedKeyForKey`.`
*/
FOUNDATION_EXPORT NSString * _Nullable SDThumbnailedKeyForKey(NSString * _Nullable key, CGSize thumbnailPixelSize, BOOL preserveAspectRatio);
/**
A transformer protocol to transform the image load from cache or from download.
You can provide transformer to cache and manager (Through the `transformer` property or context option `SDWebImageContextImageTransformer`).
From v5.20, the transformer class also can be used on animated image frame post-transform logic, see `SDAnimatedImageView`.
@note The transform process is called from a global queue in order to not to block the main queue.
*/
@protocol SDImageTransformer <NSObject>
@optional
/**
Defaults to YES if you don't implements this method.
We keep some metadata like Image Format (`sd_imageFormat`)/ Animated Loop Count (`sd_imageLoopCount`) via associated object on UIImage instance.
When transformer generate a new UIImage instance, in most cases you still want to keep these information. So this is what for during the image loading pipeline.
If the value is YES, we will keep and override the metadata **After you generate the UIImage**
If the value is NO, we will not touch the UIImage metadata and it's controlled by you during the generation. Read `UIImage+Medata.h` and pick the metadata you want for the new generated UIImage.
*/
@property (nonatomic, assign, readonly) BOOL preserveImageMetadata;
@required
/**
For each transformer, it must contains its cache key to used to store the image cache or query from the cache. This key will be appened after the original cache key generated by URL or from user.
Which means, the cache should match what your transformer logic do. The same `input image` + `transformer key`, should always generate the same `output image`.
@return The cache key to appended after the original cache key. Should not be nil.
*/
@property (nonatomic, copy, readonly, nonnull) NSString *transformerKey;
/**
Transform the image to another image.
@param image The image to be transformed
@param key The cache key associated to the image. This arg is a hint for image source, not always useful and should be nullable. In the future we will remove this arg.
@return The transformed image, or nil if transform failed
*/
- (nullable UIImage *)transformedImageWithImage:(nonnull UIImage *)image forKey:(nonnull NSString *)key API_DEPRECATED("The key arg will be removed in the future. Update your code and don't rely on that.", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
@end
#pragma mark - Pipeline
/**
Pipeline transformer. Which you can bind multiple transformers together to let the image to be transformed one by one in order and generate the final image.
@note Because transformers are lightweight, if you want to append or arrange transformers, create another pipeline transformer instead. This class is considered as immutable.
*/
@interface SDImagePipelineTransformer : NSObject<SDImageTransformer>
/// For pipeline transformer, this property is readonly and always return NO. We handle each transformer's choice inside implementation
@property (nonatomic, assign, readonly) BOOL preserveImageMetadata;
/**
All transformers in pipeline
*/
@property (nonatomic, copy, readonly, nonnull) NSArray<id<SDImageTransformer>> *transformers;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithTransformers:(nonnull NSArray<id<SDImageTransformer>> *)transformers;
@end
#pragma mark - Base
/// This is the base class for our built-in concrete transformers. You should not use this class directlly, use cconcrete subclass (like `SDImageRoundCornerTransformer`) instead.
@interface SDImageBaseTransformer : NSObject<SDImageTransformer>
/// For concrete transformer, this property is readwrite and defaults to YES. You can choose whether to preserve image metadata **After you generate the UIImage**
@property (nonatomic, assign, readwrite) BOOL preserveImageMetadata;
@end
// There are some built-in transformers based on the `UIImage+Transformer` category to provide the common image geometry, image blending and image effect process. Those transform are useful for static image only but you can create your own to support animated image as well.
// Because transformers are lightweight, these class are considered as immutable.
#pragma mark - Image Geometry
/**
Image round corner transformer
*/
@interface SDImageRoundCornerTransformer: SDImageBaseTransformer
/**
The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to
half the width or height.
*/
@property (nonatomic, assign, readonly) CGFloat cornerRadius;
/**
A bitmask value that identifies the corners that you want
rounded. You can use this parameter to round only a subset
of the corners of the rectangle.
*/
@property (nonatomic, assign, readonly) SDRectCorner corners;
/**
The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
*/
@property (nonatomic, assign, readonly) CGFloat borderWidth;
/**
The border stroke color. nil means clear color.
*/
@property (nonatomic, strong, readonly, nullable) UIColor *borderColor;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor;
@end
/**
Image resizing transformer
*/
@interface SDImageResizingTransformer : SDImageBaseTransformer
/**
The new size to be resized, values should be positive.
*/
@property (nonatomic, assign, readonly) CGSize size;
/**
The scale mode for image content.
*/
@property (nonatomic, assign, readonly) SDImageScaleMode scaleMode;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode;
@end
/**
Image cropping transformer
*/
@interface SDImageCroppingTransformer : SDImageBaseTransformer
/**
Image's inner rect.
*/
@property (nonatomic, assign, readonly) CGRect rect;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithRect:(CGRect)rect;
@end
/**
Image flipping transformer
*/
@interface SDImageFlippingTransformer : SDImageBaseTransformer
/**
YES to flip the image horizontally. ⇋
*/
@property (nonatomic, assign, readonly) BOOL horizontal;
/**
YES to flip the image vertically. ⥯
*/
@property (nonatomic, assign, readonly) BOOL vertical;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical;
@end
/**
Image rotation transformer
*/
@interface SDImageRotationTransformer : SDImageBaseTransformer
/**
Rotated radians in counterclockwise.⟲
*/
@property (nonatomic, assign, readonly) CGFloat angle;
/**
YES: new image's size is extend to fit all content.
NO: image's size will not change, content may be clipped.
*/
@property (nonatomic, assign, readonly) BOOL fitSize;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize;
@end
#pragma mark - Image Blending
/**
Image tint color transformer
*/
@interface SDImageTintTransformer : SDImageBaseTransformer
/**
The tint color.
*/
@property (nonatomic, strong, readonly, nonnull) UIColor *tintColor;
/// The blend mode, defaults to `sourceIn` if you use the initializer without blend mode
@property (nonatomic, assign, readonly) CGBlendMode blendMode;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithColor:(nonnull UIColor *)tintColor;
+ (nonnull instancetype)transformerWithColor:(nonnull UIColor *)tintColor blendMode:(CGBlendMode)blendMode;
@end
#pragma mark - Image Effect
/**
Image blur effect transformer
*/
@interface SDImageBlurTransformer : SDImageBaseTransformer
/**
The radius of the blur in points, 0 means no blur effect.
*/
@property (nonatomic, assign, readonly) CGFloat blurRadius;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithRadius:(CGFloat)blurRadius;
@end
#if SD_UIKIT || SD_MAC
/**
Core Image filter transformer
*/
@interface SDImageFilterTransformer: SDImageBaseTransformer
/**
The CIFilter to be applied to the image.
*/
@property (nonatomic, strong, readonly, nonnull) CIFilter *filter;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
+ (nonnull instancetype)transformerWithFilter:(nonnull CIFilter *)filter;
@end
#endif

View File

@@ -0,0 +1,375 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageTransformer.h"
#import "UIColor+SDHexString.h"
#import "SDAssociatedObject.h"
#if SD_UIKIT || SD_MAC
#import <CoreImage/CoreImage.h>
#endif
// Separator for different transformerKey, for example, `image.png` |> flip(YES,NO) |> rotate(pi/4,YES) => 'image-SDImageFlippingTransformer(1,0)-SDImageRotationTransformer(0.78539816339,1).png'
static NSString * const SDImageTransformerKeySeparator = @"-";
NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey) {
if (!key || !transformerKey) {
return nil;
}
// Find the file extension
NSURL *keyURL = [NSURL URLWithString:key];
NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension;
if (ext.length > 0) {
// For non-file URL
if (keyURL && !keyURL.isFileURL) {
// keep anything except path (like URL query)
NSURLComponents *component = [NSURLComponents componentsWithURL:keyURL resolvingAgainstBaseURL:NO];
component.path = [[[component.path.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext];
return component.URL.absoluteString;
} else {
// file URL
return [[[key.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext];
}
} else {
return [[key stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey];
}
}
NSString * _Nullable SDThumbnailedKeyForKey(NSString * _Nullable key, CGSize thumbnailPixelSize, BOOL preserveAspectRatio) {
NSString *thumbnailKey = [NSString stringWithFormat:@"Thumbnail({%f,%f},%d)", thumbnailPixelSize.width, thumbnailPixelSize.height, preserveAspectRatio];
return SDTransformedKeyForKey(key, thumbnailKey);
}
@interface SDImagePipelineTransformer ()
@property (nonatomic, copy, readwrite, nonnull) NSArray<id<SDImageTransformer>> *transformers;
@property (nonatomic, copy, readwrite) NSString *transformerKey;
@end
@implementation SDImagePipelineTransformer
+ (instancetype)transformerWithTransformers:(NSArray<id<SDImageTransformer>> *)transformers {
SDImagePipelineTransformer *transformer = [SDImagePipelineTransformer new];
transformer.transformers = transformers;
transformer.transformerKey = [[self class] cacheKeyForTransformers:transformers];
return transformer;
}
+ (NSString *)cacheKeyForTransformers:(NSArray<id<SDImageTransformer>> *)transformers {
if (transformers.count == 0) {
return @"";
}
NSMutableArray<NSString *> *cacheKeys = [NSMutableArray arrayWithCapacity:transformers.count];
[transformers enumerateObjectsUsingBlock:^(id<SDImageTransformer> _Nonnull transformer, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *cacheKey = transformer.transformerKey;
[cacheKeys addObject:cacheKey];
}];
return [cacheKeys componentsJoinedByString:SDImageTransformerKeySeparator];
}
- (BOOL)preserveImageMetadata {
return NO; // We handle this logic inside `transformedImageWithImage` below
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
UIImage *transformedImage = image;
for (id<SDImageTransformer> transformer in self.transformers) {
UIImage *newImage = [transformer transformedImageWithImage:transformedImage forKey:key];
// Handle each transformer's preserveImageMetadata choice
BOOL preserveImageMetadata = YES;
if ([transformer respondsToSelector:@selector(preserveImageMetadata)]) {
preserveImageMetadata = transformer.preserveImageMetadata;
}
if (preserveImageMetadata) {
SDImageCopyAssociatedObject(transformedImage, newImage);
}
transformedImage = newImage;
}
return transformedImage;
}
@end
@implementation SDImageBaseTransformer
- (instancetype)init {
self = [super init];
if (self) {
_preserveImageMetadata = YES;
}
return self;
}
- (NSString *)transformerKey {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:[NSString stringWithFormat:@"For `SDImageBaseTransformer` subclass, you must override %@ method", NSStringFromSelector(_cmd)]
userInfo:nil];
}
- (nullable UIImage *)transformedImageWithImage:(nonnull UIImage *)image forKey:(nonnull NSString *)key {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:[NSString stringWithFormat:@"For `SDImageBaseTransformer` subclass, you must override %@ method", NSStringFromSelector(_cmd)]
userInfo:nil];
}
@end
@interface SDImageRoundCornerTransformer ()
@property (nonatomic, assign) CGFloat cornerRadius;
@property (nonatomic, assign) SDRectCorner corners;
@property (nonatomic, assign) CGFloat borderWidth;
@property (nonatomic, strong, nullable) UIColor *borderColor;
@end
@implementation SDImageRoundCornerTransformer
+ (instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
SDImageRoundCornerTransformer *transformer = [SDImageRoundCornerTransformer new];
transformer.cornerRadius = cornerRadius;
transformer.corners = corners;
transformer.borderWidth = borderWidth;
transformer.borderColor = borderColor;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageRoundCornerTransformer(%f,%lu,%f,%@)", self.cornerRadius, (unsigned long)self.corners, self.borderWidth, self.borderColor.sd_hexString];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_roundedCornerImageWithRadius:self.cornerRadius corners:self.corners borderWidth:self.borderWidth borderColor:self.borderColor];
}
@end
@interface SDImageResizingTransformer ()
@property (nonatomic, assign) CGSize size;
@property (nonatomic, assign) SDImageScaleMode scaleMode;
@end
@implementation SDImageResizingTransformer
+ (instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode {
SDImageResizingTransformer *transformer = [SDImageResizingTransformer new];
transformer.size = size;
transformer.scaleMode = scaleMode;
return transformer;
}
- (NSString *)transformerKey {
CGSize size = self.size;
return [NSString stringWithFormat:@"SDImageResizingTransformer({%f,%f},%lu)", size.width, size.height, (unsigned long)self.scaleMode];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_resizedImageWithSize:self.size scaleMode:self.scaleMode];
}
@end
@interface SDImageCroppingTransformer ()
@property (nonatomic, assign) CGRect rect;
@end
@implementation SDImageCroppingTransformer
+ (instancetype)transformerWithRect:(CGRect)rect {
SDImageCroppingTransformer *transformer = [SDImageCroppingTransformer new];
transformer.rect = rect;
return transformer;
}
- (NSString *)transformerKey {
CGRect rect = self.rect;
return [NSString stringWithFormat:@"SDImageCroppingTransformer({%f,%f,%f,%f})", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_croppedImageWithRect:self.rect];
}
@end
@interface SDImageFlippingTransformer ()
@property (nonatomic, assign) BOOL horizontal;
@property (nonatomic, assign) BOOL vertical;
@end
@implementation SDImageFlippingTransformer
+ (instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical {
SDImageFlippingTransformer *transformer = [SDImageFlippingTransformer new];
transformer.horizontal = horizontal;
transformer.vertical = vertical;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageFlippingTransformer(%d,%d)", self.horizontal, self.vertical];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_flippedImageWithHorizontal:self.horizontal vertical:self.vertical];
}
@end
@interface SDImageRotationTransformer ()
@property (nonatomic, assign) CGFloat angle;
@property (nonatomic, assign) BOOL fitSize;
@end
@implementation SDImageRotationTransformer
+ (instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize {
SDImageRotationTransformer *transformer = [SDImageRotationTransformer new];
transformer.angle = angle;
transformer.fitSize = fitSize;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageRotationTransformer(%f,%d)", self.angle, self.fitSize];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_rotatedImageWithAngle:self.angle fitSize:self.fitSize];
}
@end
#pragma mark - Image Blending
@interface SDImageTintTransformer ()
@property (nonatomic, strong, nonnull) UIColor *tintColor;
@property (nonatomic, assign) CGBlendMode blendMode;
@end
@implementation SDImageTintTransformer
+ (instancetype)transformerWithColor:(UIColor *)tintColor {
return [self transformerWithColor:tintColor blendMode:kCGBlendModeSourceIn];
}
+ (instancetype)transformerWithColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode {
SDImageTintTransformer *transformer = [SDImageTintTransformer new];
transformer.tintColor = tintColor;
transformer.blendMode = blendMode;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageTintTransformer(%@,%d)", self.tintColor.sd_hexString, self.blendMode];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_tintedImageWithColor:self.tintColor];
}
@end
#pragma mark - Image Effect
@interface SDImageBlurTransformer ()
@property (nonatomic, assign) CGFloat blurRadius;
@end
@implementation SDImageBlurTransformer
+ (instancetype)transformerWithRadius:(CGFloat)blurRadius {
SDImageBlurTransformer *transformer = [SDImageBlurTransformer new];
transformer.blurRadius = blurRadius;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageBlurTransformer(%f)", self.blurRadius];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_blurredImageWithRadius:self.blurRadius];
}
@end
#if SD_UIKIT || SD_MAC
@interface SDImageFilterTransformer ()
@property (nonatomic, strong, nonnull) CIFilter *filter;
@end
@implementation SDImageFilterTransformer
+ (instancetype)transformerWithFilter:(CIFilter *)filter {
SDImageFilterTransformer *transformer = [SDImageFilterTransformer new];
transformer.filter = filter;
return transformer;
}
- (NSString *)transformerKey {
return [NSString stringWithFormat:@"SDImageFilterTransformer(%@)", self.filter.name];
}
- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key {
if (!image) {
return nil;
}
return [image sd_filteredImageWithFilter:self.filter];
}
@end
#endif

View File

@@ -0,0 +1,78 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
@class SDImageCacheConfig;
/**
A protocol to allow custom memory cache used in SDImageCache.
*/
@protocol SDMemoryCache <NSObject>
@required
/**
Create a new memory cache instance with the specify cache config. You can check `maxMemoryCost` and `maxMemoryCount` used for memory cache.
@param config The cache config to be used to create the cache.
@return The new memory cache instance.
*/
- (nonnull instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config;
/**
Returns the value associated with a given key.
@param key An object identifying the value. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable id)objectForKey:(nonnull id)key;
/**
Sets the value of the specified key in the cache (0 cost).
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param key The key with which to associate the value. If nil, this method has no effect.
@discussion Unlike an NSMutableDictionary object, a cache does not copy the key
objects that are put into it.
*/
- (void)setObject:(nullable id)object forKey:(nonnull id)key;
/**
Sets the value of the specified key in the cache, and associates the key-value
pair with the specified cost.
@param object The object to store in the cache. If nil, it calls `removeObjectForKey`.
@param key The key with which to associate the value. If nil, this method has no effect.
@param cost The cost with which to associate the key-value pair.
@discussion Unlike an NSMutableDictionary object, a cache does not copy the key
objects that are put into it.
*/
- (void)setObject:(nullable id)object forKey:(nonnull id)key cost:(NSUInteger)cost;
/**
Removes the value of the specified key in the cache.
@param key The key identifying the value to be removed. If nil, this method has no effect.
*/
- (void)removeObjectForKey:(nonnull id)key;
/**
Empties the cache immediately.
*/
- (void)removeAllObjects;
@end
/**
A memory cache which auto purge the cache on memory warning and support weak cache.
*/
@interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType> <SDMemoryCache>
@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;
@end

View File

@@ -0,0 +1,158 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDMemoryCache.h"
#import "SDImageCacheConfig.h"
#import "UIImage+MemoryCacheCost.h"
#import "SDInternalMacros.h"
static void * SDMemoryCacheContext = &SDMemoryCacheContext;
@interface SDMemoryCache <KeyType, ObjectType> () {
#if SD_UIKIT
SD_LOCK_DECLARE(_weakCacheLock); // a lock to keep the access to `weakCache` thread-safe
#endif
}
@property (nonatomic, strong, nullable) SDImageCacheConfig *config;
#if SD_UIKIT
@property (nonatomic, strong, nonnull) NSMapTable<KeyType, ObjectType> *weakCache; // strong-weak cache
#endif
@end
@implementation SDMemoryCache
- (void)dealloc {
[_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) context:SDMemoryCacheContext];
[_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) context:SDMemoryCacheContext];
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
self.delegate = nil;
}
- (instancetype)init {
self = [super init];
if (self) {
_config = [[SDImageCacheConfig alloc] init];
[self commonInit];
}
return self;
}
- (instancetype)initWithConfig:(SDImageCacheConfig *)config {
self = [super init];
if (self) {
_config = config;
[self commonInit];
}
return self;
}
- (void)commonInit {
SDImageCacheConfig *config = self.config;
self.totalCostLimit = config.maxMemoryCost;
self.countLimit = config.maxMemoryCount;
[config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) options:0 context:SDMemoryCacheContext];
[config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) options:0 context:SDMemoryCacheContext];
#if SD_UIKIT
self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
SD_LOCK_INIT(_weakCacheLock);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
#endif
}
// Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform.
#if SD_UIKIT
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
// Only remove cache, but keep weak cache
[super removeAllObjects];
}
// `setObject:forKey:` just call this with 0 cost. Override this is enough
- (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g {
[super setObject:obj forKey:key cost:g];
if (!self.config.shouldUseWeakMemoryCache) {
return;
}
if (key && obj) {
// Store weak cache
SD_LOCK(_weakCacheLock);
[self.weakCache setObject:obj forKey:key];
SD_UNLOCK(_weakCacheLock);
}
}
- (id)objectForKey:(id)key {
id obj = [super objectForKey:key];
if (!self.config.shouldUseWeakMemoryCache) {
return obj;
}
if (key && !obj) {
// Check weak cache
SD_LOCK(_weakCacheLock);
obj = [self.weakCache objectForKey:key];
SD_UNLOCK(_weakCacheLock);
if (obj) {
// Sync cache
NSUInteger cost = 0;
if ([obj isKindOfClass:[UIImage class]]) {
cost = [(UIImage *)obj sd_memoryCost];
}
[super setObject:obj forKey:key cost:cost];
}
}
return obj;
}
- (void)removeObjectForKey:(id)key {
[super removeObjectForKey:key];
if (!self.config.shouldUseWeakMemoryCache) {
return;
}
if (key) {
// Remove weak cache
SD_LOCK(_weakCacheLock);
[self.weakCache removeObjectForKey:key];
SD_UNLOCK(_weakCacheLock);
}
}
- (void)removeAllObjects {
[super removeAllObjects];
if (!self.config.shouldUseWeakMemoryCache) {
return;
}
// Manually remove should also remove weak cache
SD_LOCK(_weakCacheLock);
[self.weakCache removeAllObjects];
SD_UNLOCK(_weakCacheLock);
}
#endif
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (context == SDMemoryCacheContext) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCost))]) {
self.totalCostLimit = self.config.maxMemoryCost;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCount))]) {
self.countLimit = self.config.maxMemoryCount;
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end

View File

@@ -0,0 +1,35 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
typedef NSString * _Nullable(^SDWebImageCacheKeyFilterBlock)(NSURL * _Nonnull url);
/**
This is the protocol for cache key filter.
We can use a block to specify the cache key filter. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options.
*/
@protocol SDWebImageCacheKeyFilter <NSObject>
- (nullable NSString *)cacheKeyForURL:(nonnull NSURL *)url;
@end
/**
A cache key filter class with block.
*/
@interface SDWebImageCacheKeyFilter : NSObject <SDWebImageCacheKeyFilter>
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block;
+ (nonnull instancetype)cacheKeyFilterWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block;
@end

View File

@@ -0,0 +1,39 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCacheKeyFilter.h"
@interface SDWebImageCacheKeyFilter ()
@property (nonatomic, copy, nonnull) SDWebImageCacheKeyFilterBlock block;
@end
@implementation SDWebImageCacheKeyFilter
- (instancetype)initWithBlock:(SDWebImageCacheKeyFilterBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)cacheKeyFilterWithBlock:(SDWebImageCacheKeyFilterBlock)block {
SDWebImageCacheKeyFilter *cacheKeyFilter = [[SDWebImageCacheKeyFilter alloc] initWithBlock:block];
return cacheKeyFilter;
}
- (NSString *)cacheKeyForURL:(NSURL *)url {
if (!self.block) {
return nil;
}
return self.block(url);
}
@end

View File

@@ -0,0 +1,39 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
typedef NSData * _Nullable(^SDWebImageCacheSerializerBlock)(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL);
/**
This is the protocol for cache serializer.
We can use a block to specify the cache serializer. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options.
*/
@protocol SDWebImageCacheSerializer <NSObject>
/// Provide the image data associated to the image and store to disk cache
/// @param image The loaded image
/// @param data The original loaded image data. May be nil when image is transformed (UIImage.sd_isTransformed = YES)
/// @param imageURL The image URL
- (nullable NSData *)cacheDataWithImage:(nonnull UIImage *)image originalData:(nullable NSData *)data imageURL:(nullable NSURL *)imageURL;
@end
/**
A cache serializer class with block.
*/
@interface SDWebImageCacheSerializer : NSObject <SDWebImageCacheSerializer>
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheSerializerBlock)block;
+ (nonnull instancetype)cacheSerializerWithBlock:(nonnull SDWebImageCacheSerializerBlock)block;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end

View File

@@ -0,0 +1,39 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCacheSerializer.h"
@interface SDWebImageCacheSerializer ()
@property (nonatomic, copy, nonnull) SDWebImageCacheSerializerBlock block;
@end
@implementation SDWebImageCacheSerializer
- (instancetype)initWithBlock:(SDWebImageCacheSerializerBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)cacheSerializerWithBlock:(SDWebImageCacheSerializerBlock)block {
SDWebImageCacheSerializer *cacheSerializer = [[SDWebImageCacheSerializer alloc] initWithBlock:block];
return cacheSerializer;
}
- (NSData *)cacheDataWithImage:(UIImage *)image originalData:(NSData *)data imageURL:(nullable NSURL *)imageURL {
if (!self.block) {
return nil;
}
return self.block(image, data, imageURL);
}
@end

View File

@@ -0,0 +1,102 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Jamie Pinkham
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <TargetConditionals.h>
#ifdef __OBJC_GC__
#error SDWebImage does not support Objective-C Garbage Collection
#endif
// Seems like TARGET_OS_MAC is always defined (on all platforms).
// To determine if we are running on macOS, use TARGET_OS_OSX in Xcode 8
#if TARGET_OS_OSX
#define SD_MAC 1
#else
#define SD_MAC 0
#endif
#if TARGET_OS_IOS
#define SD_IOS 1
#else
#define SD_IOS 0
#endif
#if TARGET_OS_TV
#define SD_TV 1
#else
#define SD_TV 0
#endif
#if TARGET_OS_WATCH
#define SD_WATCH 1
#else
#define SD_WATCH 0
#endif
// Supports Xcode 14 to suppress warning
#ifdef TARGET_OS_VISION
#if TARGET_OS_VISION
#define SD_VISION 1
#endif
#endif
// iOS/tvOS/visionOS are very similar, UIKit exists on both platforms
// Note: watchOS also has UIKit, but it's very limited
#if SD_IOS || SD_TV || SD_VISION
#define SD_UIKIT 1
#else
#define SD_UIKIT 0
#endif
#if SD_MAC
#import <AppKit/AppKit.h>
#ifndef UIImage
#define UIImage NSImage
#endif
#ifndef UIImageView
#define UIImageView NSImageView
#endif
#ifndef UIView
#define UIView NSView
#endif
#ifndef UIColor
#define UIColor NSColor
#endif
#else
#if SD_UIKIT
#import <UIKit/UIKit.h>
#endif
#if SD_WATCH
#import <WatchKit/WatchKit.h>
#ifndef UIView
#define UIView WKInterfaceObject
#endif
#ifndef UIImageView
#define UIImageView WKInterfaceImage
#endif
#endif
#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
#ifndef dispatch_main_async_safe
#define dispatch_main_async_safe(block)\
if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#pragma clang deprecated(dispatch_main_async_safe, "Use SDCallbackQueue instead")
#endif

View File

@@ -0,0 +1,17 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#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
#if !OS_OBJECT_USE_OBJC
#error SDWebImage need ARC for dispatch object
#endif

View File

@@ -0,0 +1,420 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
typedef void(^SDWebImageNoParamsBlock)(void);
/// Image Loading context option
typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM;
typedef NSDictionary<SDWebImageContextOption, id> SDWebImageContext;
typedef NSMutableDictionary<SDWebImageContextOption, id> SDWebImageMutableContext;
#pragma mark - Image scale
/**
Return the image scale factor for the specify key, supports file name and url key.
This is the built-in way to check the scale factor when we have no context about it. Because scale factor is not stored in image data (It's typically from filename).
However, you can also provide custom scale factor as well, see `SDWebImageContextImageScaleFactor`.
@param key The image cache key
@return The scale factor for image
*/
FOUNDATION_EXPORT CGFloat SDImageScaleFactorForKey(NSString * _Nullable key);
/**
Scale the image with the scale factor for the specify key. If no need to scale, return the original image.
This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`.
@note This is actually a convenience function, which firstly call `SDImageScaleFactorForKey` and then call `SDScaledImageForScaleFactor`, kept for backward compatibility.
@param key The image cache key
@param image The image
@return The scaled image
*/
FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image);
/**
Scale the image with the scale factor. If no need to scale, return the original image.
This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`.
@param scale The image scale factor
@param image The image
@return The scaled image
*/
FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image);
#pragma mark - WebCache Options
/// WebCache options
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 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.
*/
SDWebImageProgressiveLoad = 1 << 2,
/**
* 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 embedded cache busting parameter.
*/
SDWebImageRefreshCached = 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.
*/
SDWebImageContinueInBackground = 1 << 4,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
SDWebImageHandleCookies = 1 << 5,
/**
* Enable to allow untrusted SSL certificates.
* Useful for testing purposes. Use with caution in production.
*/
SDWebImageAllowInvalidSSLCertificates = 1 << 6,
/**
* By default, images are loaded in the order in which they were queued. This flag moves them to
* the front of the queue.
*/
SDWebImageHighPriority = 1 << 7,
/**
* By default, placeholder images are loaded while the image is loading. This flag will delay the loading
* of the placeholder image until after the image has finished loading.
* @note This is used to treate placeholder as an **Error Placeholder** but not **Loading Placeholder** by defaults. if the image loading is cancelled or error, the placeholder will be always set.
* @note Therefore, if you want both **Error Placeholder** and **Loading Placeholder** exist, use `SDWebImageAvoidAutoSetImage` to manually set the two placeholders and final loaded image by your hand depends on loading result.
* @note This options is UI level options, has no usage on ImageManager or other components.
*/
SDWebImageDelayPlaceholder = 1 << 8,
/**
* We usually don't apply transform on animated images as most transformers could not manage animated images.
* Use this flag to transform them anyway.
*/
SDWebImageTransformAnimatedImage = 1 << 9,
/**
* By default, image is added to the imageView after download. But in some cases, we want to
* have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
* Use this flag if you want to manually set the image in the completion when success
* @note This options is UI level options, has no usage on ImageManager or other components.
*/
SDWebImageAvoidAutoSetImage = 1 << 10,
/**
* By default, images are decoded respecting their original size.
* This flag will scale down the images to a size compatible with the constrained memory of devices.
* To control the limit memory bytes, check `SDImageCoderHelper.defaultScaleDownLimitBytes` (Defaults to 60MB on iOS)
* (from 5.16.0) This will actually translate to use context option `SDWebImageContextImageScaleDownLimitBytes`, which check and calculate the thumbnail pixel size occupied small than limit bytes (including animated image)
* (from 5.5.0) This flags effect the progressive and animated images as well
* @note If you need detail controls, it's better to use context option `imageScaleDownBytes` instead.
* @warning This does not effect the cache key. So which means, this will effect the global cache even next time you query without this option. Pay attention when you use this on global options (It's always recommended to use request-level option for different pipeline)
*/
SDWebImageScaleDownLargeImages = 1 << 11,
/**
* By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDWebImageQueryMemoryDataSync`
*/
SDWebImageQueryMemoryData = 1 << 12,
/**
* By default, when you only specify `SDWebImageQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously.
* @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing.
*/
SDWebImageQueryMemoryDataSync = 1 << 13,
/**
* By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously.
* @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page.
* @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing.
*/
SDWebImageQueryDiskDataSync = 1 << 14,
/**
* By default, when the cache missed, the image is load from the loader. This flag can prevent this to load from cache only.
*/
SDWebImageFromCacheOnly = 1 << 15,
/**
* By default, we query the cache before the image is load from the loader. This flag can prevent this to load from loader only.
*/
SDWebImageFromLoaderOnly = 1 << 16,
/**
* By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image when the callback from manager is asynchronous (from network, or disk cache query)
* This mask can force to apply view transition for any cases, like memory cache query, or sync disk cache query.
* @note This options is UI level options, has no usage on ImageManager or other components.
*/
SDWebImageForceTransition = 1 << 17,
/**
* By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation.
* However, this process may increase the memory usage as well. If you are experiencing an issue due to excessive memory consumption, This flag can prevent decode the image.
* @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not)
* @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option
*/
SDWebImageAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 18,
/**
* By default, we decode the animated image. This flag can force decode the first frame only and produce the static image.
*/
SDWebImageDecodeFirstFrameOnly = 1 << 19,
/**
* By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. However, you can specify to preload all frames into memory to reduce CPU usage when the animated image is shared by lots of imageViews.
* This will actually trigger `preloadAllAnimatedImageFrames` in the background queue(Disk Cache & Download only).
*/
SDWebImagePreloadAllFrames = 1 << 20,
/**
* By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available to produce one exactlly matching your custom class as a fallback solution.
* Using this option, can ensure we always callback image with your provided class. If failed to produce one, a error with code `SDWebImageErrorBadImageData` will been used.
* Note this options is not compatible with `SDWebImageDecodeFirstFrameOnly`, which always produce a UIImage/NSImage.
*/
SDWebImageMatchAnimatedImageClass = 1 << 21,
/**
* By default, when we load the image from network, the image will be written to the cache (memory and disk, controlled by your `storeCacheType` context option)
* This maybe an asynchronously operation and the final `SDInternalCompletionBlock` callback does not guarantee the disk cache written is finished and may cause logic error. (For example, you modify the disk data just in completion block, however, the disk cache is not ready)
* If you need to process with the disk cache in the completion block, you should use this option to ensure the disk cache already been written when callback.
* Note if you use this when using the custom cache serializer, or using the transformer, we will also wait until the output image data written is finished.
*/
SDWebImageWaitStoreCache = 1 << 22,
/**
* We usually don't apply transform on vector images, because vector images supports dynamically changing to any size, rasterize to a fixed size will loss details. To modify vector images, you can process the vector data at runtime (such as modifying PDF tag / SVG element).
* Use this flag to transform them anyway.
*/
SDWebImageTransformVectorImage = 1 << 23,
/**
* By defaults, when you use UI-level category like `sd_setImageWithURL:` on UIImageView, it will cancel the loading image requests.
* However, some users may choose to not cancel the loading image requests and always start new pipeline.
* Use this flag to disable automatic cancel behavior.
* @note This options is UI level options, has no usage on ImageManager or other components.
*/
SDWebImageAvoidAutoCancelImage = 1 << 24,
/**
* By defaults, for `SDWebImageTransition`, we just submit to UI transition and inmeediatelly callback the final `completedBlock` (`SDExternalCompletionBlock/SDInternalCompletionBlock`).
* This may cause un-wanted behavior if you do another transition inside `completedBlock`, because the previous transition is still runnning and un-cancellable, which mass-up the UI status.
* For this case, you can pass this option, we will delay the final callback, until your transition end. So when you inside `completedBlock`, no any transition is running on image view and safe to submit new transition.
* @note Currently we do not support `pausable/cancellable` transition. But possible in the future by using the https://developer.apple.com/documentation/uikit/uiviewpropertyanimator.
* @note If you have complicated transition animation, just use `SDWebImageManager` and do UI state management by yourself, do not use the top-level API (`sd_setImageWithURL:`)
*/
SDWebImageWaitTransition = 1 << 25,
};
#pragma mark - Manager Context Options
/**
A String to be used as the operation key for view category to store the image load operation. This is used for view instance which supports different image loading process. If nil, will use the class name as operation key. (NSString *)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextSetImageOperationKey;
/**
A SDWebImageManager instance to control the image download and cache process using in UIImageView+WebCache category and likes. If not provided, use the shared manager (SDWebImageManager *)
@deprecated Deprecated in the future. This context options can be replaced by other context option control like `.imageCache`, `.imageLoader`, `.imageTransformer` (See below), which already matches all the properties in SDWebImageManager.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCustomManager API_DEPRECATED("Use individual context option like .imageCache, .imageLoader and .imageTransformer instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
/**
A `SDCallbackQueue` instance which controls the `Cache`/`Manager`/`Loader`'s callback queue for their completionBlock.
This is useful for user who call these 3 components in non-main queue and want to avoid callback in main queue.
@note For UI callback (`sd_setImageWithURL`), we will still use main queue to dispatch, means if you specify a global queue, it will enqueue from the global queue to main queue.
@note This does not effect the components' working queue (for example, `Cache` still query disk on internal ioQueue, `Loader` still do network on URLSessionConfiguration.delegateQueue), change those config if you need.
Defaults to nil. Which means main queue.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCallbackQueue;
/**
A id<SDImageCache> instance which conforms to `SDImageCache` protocol. It's used to override the image manager's cache during the image loading pipeline.
In other word, if you just want to specify a custom cache during image loading, you don't need to re-create a dummy SDWebImageManager instance with the cache. If not provided, use the image manager's cache (id<SDImageCache>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageCache;
/**
A id<SDImageLoader> instance which conforms to `SDImageLoader` protocol. It's used to override the image manager's loader during the image loading pipeline.
In other word, if you just want to specify a custom loader during image loading, you don't need to re-create a dummy SDWebImageManager instance with the loader. If not provided, use the image manager's cache (id<SDImageLoader>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageLoader;
/**
A id<SDImageCoder> instance which conforms to `SDImageCoder` protocol. It's used to override the default image coder for image decoding(including progressive) and encoding during the image loading process.
If you use this context option, we will not always use `SDImageCodersManager.shared` to loop through all registered coders and find the suitable one. Instead, we will arbitrarily use the exact provided coder without extra checking (We may not call `canDecodeFromData:`).
@note This is only useful for cases which you can ensure the loading url matches your coder, or you find it's too hard to write a common coder which can used for generic usage. This will bind the loading url with the coder logic, which is not always a good design, but possible. (id<SDImageCache>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageCoder;
/**
A id<SDImageTransformer> instance which conforms `SDImageTransformer` protocol. It's used for image transform after the image load finished and store the transformed image to cache. If you provide one, it will ignore the `transformer` in manager and use provided one instead. If you pass NSNull, the transformer feature will be disabled. (id<SDImageTransformer>)
@note When this value is used, we will trigger image transform after downloaded, and the callback's data **will be nil** (because this time the data saved to disk does not match the image return to you. If you need full size data, query the cache with full size url key)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTransformer;
#pragma mark - Force Decode Options
/**
A NSNumber instance which store the`SDImageForceDecodePolicy` enum. This is used to control how current image loading should force-decode the decoded image (CGImage, typically). See more what's force-decode means in `SDImageForceDecodePolicy` comment.
Defaults to `SDImageForceDecodePolicyAutomatic`, which will detect the input CGImage's metadata, and only force-decode if the input CGImage can not directly render on screen (need extra CoreAnimation Copied Image and increase RAM usage).
@note If you want to always the force-decode for this image request, pass `SDImageForceDecodePolicyAlways`, for example, some WebP images which does not created by ImageIO.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageForceDecodePolicy;
#pragma mark - Image Decoder Context Options
/**
A Dictionary (SDImageCoderOptions) value, which pass the extra decoding options to the SDImageCoder. Introduced in SDWebImage 5.14.0
You can pass additional decoding related options to the decoder, extensible and control by you. And pay attention this dictionary may be retained by decoded image via `UIImage.sd_decodeOptions`
This context option replace the deprecated `SDImageCoderWebImageContext`, which may cause retain cycle (cache -> image -> options -> context -> cache)
@note There are already individual options below like `.imageScaleFactor`, `.imagePreserveAspectRatio`, each of individual options will override the same filed for this dictionary.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageDecodeOptions;
/**
A CGFloat raw value which specify the image scale factor. The number should be greater than or equal to 1.0. If not provide or the number is invalid, we will use the cache key to specify the scale factor. (NSNumber)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleFactor;
/**
A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format).
Defaults to YES. (NSNumber)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImagePreserveAspectRatio;
/**
A CGSize raw value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.imagePreserveAspectRatio`) the value size.
@note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both.
Defaults to CGSizeZero, which means no thumbnail generation at all. (NSValue)
@note When this value is used, we will trigger thumbnail decoding for url, and the callback's data **will be nil** (because this time the data saved to disk does not match the image return to you. If you need full size data, query the cache with full size url key)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageThumbnailPixelSize;
/**
A NSString value (UTI) indicating the source image's file extension. Example: "public.jpeg-2000", "com.nikon.raw-image", "public.tiff"
Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF
Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser
@note If you don't provide this option, we will use the `URL.path` as file extension to calculate the UTI hint
@note If you really don't want any hint which effect the image result, pass `NSNull.null` instead
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTypeIdentifierHint;
/**
A NSUInteger value to provide the limit bytes during decoding. This can help to avoid OOM on large frame count animated image or large pixel static image when you don't know how much RAM it occupied before decoding
The decoder will do these logic based on limit bytes:
1. Get the total frame count (static image means 1)
2. Calculate the `framePixelSize` width/height to `sqrt(limitBytes / frameCount / bytesPerPixel)`, keeping aspect ratio (at least 1x1)
3. If the `framePixelSize < originalImagePixelSize`, then do thumbnail decoding (see `SDImageCoderDecodeThumbnailPixelSize`) use the `framePixelSize` and `preseveAspectRatio = YES`
4. Else, use the full pixel decoding (small than limit bytes)
5. Whatever result, this does not effect the animated/static behavior of image. So even if you set `limitBytes = 1 && frameCount = 100`, we will stll create animated image with each frame `1x1` pixel size.
@note This option has higher priority than `.imageThumbnailPixelSize`
@warning This does not effect the cache key. So which means, this will effect the global cache even next time you query without this option. Pay attention when you use this on global options (It's always recommended to use request-level option for different pipeline)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleDownLimitBytes;
/**
A Boolean value (NSNumber) to provide converting to HDR during decoding. Currently if number is 0, use SDR, else use HDR. But we may extend this option to use `NSUInteger` in the future (means, think this options as int number, but not actual boolean)
@note Supported by iOS 17 and above when using ImageIO coder (third-party coder can support lower firmware)
Defaults to @(NO), decoder will automatically convert SDR.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageDecodeToHDR;
#pragma mark - Cache Context Options
/**
A Dictionary (SDImageCoderOptions) value, which pass the extra encode options to the SDImageCoder. Introduced in SDWebImage 5.15.0
You can pass encode options like `compressionQuality`, `maxFileSize`, `maxPixelSize` to control the encoding related thing, this is used inside `SDImageCache` during store logic.
@note For developer who use custom cache protocol (not SDImageCache instance), they need to upgrade and use these options for encoding.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageEncodeOptions;
/**
A SDImageCacheType raw value which specify the source of cache to query. Specify `SDImageCacheTypeDisk` to query from disk cache only; `SDImageCacheTypeMemory` to query from memory only. And `SDImageCacheTypeAll` to query from both memory cache and disk cache. Specify `SDImageCacheTypeNone` is invalid and totally ignore the cache query.
If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextQueryCacheType;
/**
A SDImageCacheType raw value which specify the store cache type when the image has just been downloaded and will be stored to the cache. Specify `SDImageCacheTypeNone` to disable cache storage; `SDImageCacheTypeDisk` to store in disk cache only; `SDImageCacheTypeMemory` to store in memory only. And `SDImageCacheTypeAll` to store in both memory cache and disk cache.
If you use image transformer feature, this actually apply for the transformed image, but not the original image itself. Use `SDWebImageContextOriginalStoreCacheType` if you want to control the original image's store cache type at the same time.
If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextStoreCacheType;
/**
The same behavior like `SDWebImageContextQueryCacheType`, but control the query cache type for the original image when you use image transformer feature. This allows the detail control of cache query for these two images. For example, if you want to query the transformed image from both memory/disk cache, query the original image from disk cache only, use `[.queryCacheType : .all, .originalQueryCacheType : .disk]`
If not provide or the value is invalid, we will use `SDImageCacheTypeDisk`, which query the original full image data from disk cache after transformed image cache miss. This is suitable for most common cases to avoid re-downloading the full data for different transform variants. (NSNumber)
@note Which means, if you set this value to not be `.none`, we will query the original image from cache, then do transform with transformer, instead of actual downloading, which can save bandwidth usage.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalQueryCacheType;
/**
The same behavior like `SDWebImageContextStoreCacheType`, but control the store cache type for the original image when you use image transformer feature. This allows the detail control of cache storage for these two images. For example, if you want to store the transformed image into both memory/disk cache, store the original image into disk cache only, use `[.storeCacheType : .all, .originalStoreCacheType : .disk]`
If not provide or the value is invalid, we will use `SDImageCacheTypeDisk`, which store the original full image data into disk cache after storing the transformed image. This is suitable for most common cases to avoid re-downloading the full data for different transform variants. (NSNumber)
@note This only store the original image, if you want to use the original image without downloading in next query, specify `SDWebImageContextOriginalQueryCacheType` as well.
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalStoreCacheType;
/**
A id<SDImageCache> instance which conforms to `SDImageCache` protocol. It's used to control the cache for original image when using the transformer. If you provide one, the original image (full size image) will query and write from that cache instance instead, the transformed image will query and write from the default `SDWebImageContextImageCache` instead. (id<SDImageCache>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalImageCache;
/**
A Class object which the instance is a `UIImage/NSImage` subclass and adopt `SDAnimatedImage` protocol. We will call `initWithData:scale:options:` to create the instance (or `initWithAnimatedCoder:scale:` when using progressive download) . If the instance create failed, fallback to normal `UIImage/NSImage`.
This can be used to improve animated images rendering performance (especially memory usage on big animated images) with `SDAnimatedImageView` (Class).
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextAnimatedImageClass;
#pragma mark - Download Context Options
/**
A id<SDWebImageDownloaderRequestModifier> instance to modify the image download request. It's used for downloader to modify the original request from URL and options. If you provide one, it will ignore the `requestModifier` in downloader and use provided one instead. (id<SDWebImageDownloaderRequestModifier>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadRequestModifier;
/**
A id<SDWebImageDownloaderResponseModifier> instance to modify the image download response. It's used for downloader to modify the original response from URL and options. If you provide one, it will ignore the `responseModifier` in downloader and use provided one instead. (id<SDWebImageDownloaderResponseModifier>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadResponseModifier;
/**
A id<SDWebImageContextDownloadDecryptor> instance to decrypt the image download data. This can be used for image data decryption, such as Base64 encoded image. If you provide one, it will ignore the `decryptor` in downloader and use provided one instead. (id<SDWebImageContextDownloadDecryptor>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadDecryptor;
/**
A id<SDWebImageCacheKeyFilter> instance to convert an URL into a cache key. It's used when manager need cache key to use image cache. If you provide one, it will ignore the `cacheKeyFilter` in manager and use provided one instead. (id<SDWebImageCacheKeyFilter>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheKeyFilter;
/**
A id<SDWebImageCacheSerializer> instance to convert the decoded image, the source downloaded data, to the actual data. It's used for manager to store image to the disk cache. If you provide one, it will ignore the `cacheSerializer` in manager and use provided one instead. (id<SDWebImageCacheSerializer>)
*/
FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheSerializer;

View File

@@ -0,0 +1,163 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDefine.h"
#import "UIImage+Metadata.h"
#import "NSImage+Compatibility.h"
#import "SDAnimatedImage.h"
#import "SDAssociatedObject.h"
#pragma mark - Image scale
static inline NSArray<NSNumber *> * _Nonnull SDImageScaleFactors(void) {
return @[@2, @3];
}
inline CGFloat SDImageScaleFactorForKey(NSString * _Nullable key) {
CGFloat scale = 1;
if (!key) {
return scale;
}
// Now all OS supports retina display scale system
{
// a@2x.png -> 8
if (key.length >= 8) {
// Fast check
BOOL isURL = [key hasPrefix:@"http://"] || [key hasPrefix:@"https://"];
for (NSNumber *scaleFactor in SDImageScaleFactors()) {
// @2x. for file name and normal url
NSString *fileScale = [NSString stringWithFormat:@"@%@x.", scaleFactor];
if ([key containsString:fileScale]) {
scale = scaleFactor.doubleValue;
return scale;
}
if (isURL) {
// %402x. for url encode
NSString *urlScale = [NSString stringWithFormat:@"%%40%@x.", scaleFactor];
if ([key containsString:urlScale]) {
scale = scaleFactor.doubleValue;
return scale;
}
}
}
}
}
return scale;
}
inline UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) {
if (!image) {
return nil;
}
CGFloat scale = SDImageScaleFactorForKey(key);
return SDScaledImageForScaleFactor(scale, image);
}
inline UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image) {
if (!image) {
return nil;
}
if (scale <= 1) {
return image;
}
if (scale == image.scale) {
return image;
}
UIImage *scaledImage;
// Check SDAnimatedImage support for shortcut
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) {
if ([image respondsToSelector:@selector(animatedCoder)]) {
id<SDAnimatedImageCoder> coder = [(id<SDAnimatedImage>)image animatedCoder];
if (coder) {
scaledImage = [[image.class alloc] initWithAnimatedCoder:coder scale:scale];
}
} else {
// Some class impl does not support `animatedCoder`, keep for compatibility
NSData *data = [(id<SDAnimatedImage>)image animatedImageData];
if (data) {
scaledImage = [[image.class alloc] initWithData:data scale:scale];
}
}
}
if (scaledImage) {
SDImageCopyAssociatedObject(image, scaledImage);
return scaledImage;
}
if (image.sd_isAnimated) {
UIImage *animatedImage;
#if SD_UIKIT || SD_WATCH
// `UIAnimatedImage` images share the same size and scale.
NSArray<UIImage *> *images = image.images;
NSMutableArray<UIImage *> *scaledImages = [NSMutableArray arrayWithCapacity:images.count];
for (UIImage *tempImage in images) {
UIImage *tempScaledImage = [[UIImage alloc] initWithCGImage:tempImage.CGImage scale:scale orientation:tempImage.imageOrientation];
[scaledImages addObject:tempScaledImage];
}
animatedImage = [UIImage animatedImageWithImages:scaledImages duration:image.duration];
#else
// Animated GIF for `NSImage` need to grab `NSBitmapImageRep`;
NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height);
NSImageRep *imageRep = [image bestRepresentationForRect:imageRect context:nil hints:nil];
NSBitmapImageRep *bitmapImageRep;
if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) {
bitmapImageRep = (NSBitmapImageRep *)imageRep;
}
if (bitmapImageRep) {
NSSize size = NSMakeSize(image.size.width / scale, image.size.height / scale);
animatedImage = [[NSImage alloc] initWithSize:size];
bitmapImageRep.size = size;
[animatedImage addRepresentation:bitmapImageRep];
}
#endif
scaledImage = animatedImage;
} else {
#if SD_UIKIT || SD_WATCH
scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
#else
scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:kCGImagePropertyOrientationUp];
#endif
}
if (scaledImage) {
SDImageCopyAssociatedObject(image, scaledImage);
return scaledImage;
}
return nil;
}
#pragma mark - Context option
SDWebImageContextOption const SDWebImageContextSetImageOperationKey = @"setImageOperationKey";
SDWebImageContextOption const SDWebImageContextCustomManager = @"customManager";
SDWebImageContextOption const SDWebImageContextCallbackQueue = @"callbackQueue";
SDWebImageContextOption const SDWebImageContextImageCache = @"imageCache";
SDWebImageContextOption const SDWebImageContextImageLoader = @"imageLoader";
SDWebImageContextOption const SDWebImageContextImageCoder = @"imageCoder";
SDWebImageContextOption const SDWebImageContextImageTransformer = @"imageTransformer";
SDWebImageContextOption const SDWebImageContextImageForceDecodePolicy = @"imageForceDecodePolicy";
SDWebImageContextOption const SDWebImageContextImageDecodeOptions = @"imageDecodeOptions";
SDWebImageContextOption const SDWebImageContextImageScaleFactor = @"imageScaleFactor";
SDWebImageContextOption const SDWebImageContextImagePreserveAspectRatio = @"imagePreserveAspectRatio";
SDWebImageContextOption const SDWebImageContextImageThumbnailPixelSize = @"imageThumbnailPixelSize";
SDWebImageContextOption const SDWebImageContextImageTypeIdentifierHint = @"imageTypeIdentifierHint";
SDWebImageContextOption const SDWebImageContextImageScaleDownLimitBytes = @"imageScaleDownLimitBytes";
SDWebImageContextOption const SDWebImageContextImageDecodeToHDR = @"imageDecodeToHDR";
SDWebImageContextOption const SDWebImageContextImageEncodeOptions = @"imageEncodeOptions";
SDWebImageContextOption const SDWebImageContextQueryCacheType = @"queryCacheType";
SDWebImageContextOption const SDWebImageContextStoreCacheType = @"storeCacheType";
SDWebImageContextOption const SDWebImageContextOriginalQueryCacheType = @"originalQueryCacheType";
SDWebImageContextOption const SDWebImageContextOriginalStoreCacheType = @"originalStoreCacheType";
SDWebImageContextOption const SDWebImageContextOriginalImageCache = @"originalImageCache";
SDWebImageContextOption const SDWebImageContextAnimatedImageClass = @"animatedImageClass";
SDWebImageContextOption const SDWebImageContextDownloadRequestModifier = @"downloadRequestModifier";
SDWebImageContextOption const SDWebImageContextDownloadResponseModifier = @"downloadResponseModifier";
SDWebImageContextOption const SDWebImageContextDownloadDecryptor = @"downloadDecryptor";
SDWebImageContextOption const SDWebImageContextCacheKeyFilter = @"cacheKeyFilter";
SDWebImageContextOption const SDWebImageContextCacheSerializer = @"cacheSerializer";

View File

@@ -0,0 +1,320 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDWebImageDefine.h"
#import "SDWebImageOperation.h"
#import "SDWebImageDownloaderConfig.h"
#import "SDWebImageDownloaderRequestModifier.h"
#import "SDWebImageDownloaderResponseModifier.h"
#import "SDWebImageDownloaderDecryptor.h"
#import "SDImageLoader.h"
/// Downloader options
typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
/**
* Put the download in the low queue priority and task priority.
*/
SDWebImageDownloaderLowPriority = 1 << 0,
/**
* This flag enables progressive download, the image is displayed progressively during download as a browser would do.
*/
SDWebImageDownloaderProgressiveLoad = 1 << 1,
/**
* By default, request prevent the use 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
* And the error code is `SDWebImageErrorCacheNotModified`
* This flag should 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 certificates.
* Useful for testing purposes. Use with caution in production.
*/
SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
/**
* Put the download in the high queue priority and task priority.
*/
SDWebImageDownloaderHighPriority = 1 << 7,
/**
* By default, images are decoded respecting their original size. On iOS, this flag will scale down the
* images to a size compatible with the constrained memory of devices.
* This flag take no effect if `SDWebImageDownloaderAvoidDecodeImage` is set. And it will be ignored if `SDWebImageDownloaderProgressiveLoad` is set.
*/
SDWebImageDownloaderScaleDownLargeImages = 1 << 8,
/**
* By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation.
* However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image.
* @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not)
* @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option
*/
SDWebImageDownloaderAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 9,
/**
* By default, we decode the animated image. This flag can force decode the first frame only and produce the static image.
*/
SDWebImageDownloaderDecodeFirstFrameOnly = 1 << 10,
/**
* By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from network
*/
SDWebImageDownloaderPreloadAllFrames = 1 << 11,
/**
* By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution.
* Using this option, can ensure we always produce image with your provided class. If failed, a error with code `SDWebImageErrorBadImageData` will been used.
* Note this options is not compatible with `SDWebImageDownloaderDecodeFirstFrameOnly`, which always produce a UIImage/NSImage.
*/
SDWebImageDownloaderMatchAnimatedImageClass = 1 << 12,
};
/// Posed when URLSessionTask started (`resume` called))
FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStartNotification;
/// Posed when URLSessionTask get HTTP response (`didReceiveResponse:completionHandler:` called)
FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadReceiveResponseNotification;
/// Posed when URLSessionTask stoped (`didCompleteWithError:` with error or `cancel` called)
FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStopNotification;
/// Posed when URLSessionTask finished with success (`didCompleteWithError:` without error)
FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadFinishNotification;
typedef SDImageLoaderProgressBlock SDWebImageDownloaderProgressBlock;
typedef SDImageLoaderCompletedBlock SDWebImageDownloaderCompletedBlock;
/**
* A token associated with each download. Can be used to cancel a download
*/
@interface SDWebImageDownloadToken : NSObject <SDWebImageOperation>
/**
Cancel the current download.
*/
- (void)cancel;
/**
The download's URL.
*/
@property (nonatomic, strong, nullable, readonly) NSURL *url;
/**
The download's request.
*/
@property (nonatomic, strong, nullable, readonly) NSURLRequest *request;
/**
The download's response.
*/
@property (nonatomic, strong, nullable, readonly) NSURLResponse *response;
/**
The download's metrics. This will be nil if download operation does not support metrics.
*/
@property (nonatomic, strong, nullable, readonly) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
@end
/**
* Asynchronous downloader dedicated and optimized for image loading.
*/
@interface SDWebImageDownloader : NSObject
/**
* Downloader Config object - storing all kind of settings.
* Most config properties support dynamic changes during download, except something like `sessionConfiguration`, see `SDWebImageDownloaderConfig` for more detail.
*/
@property (nonatomic, copy, readonly, nonnull) SDWebImageDownloaderConfig *config;
/**
* Set the request modifier to modify the original download request before image load.
* This request modifier method will be called for each downloading image request. Return the original request means no modification. Return nil will cancel the download request.
* Defaults to nil, means does not modify the original download request.
* @note If you want to modify single request, consider using `SDWebImageContextDownloadRequestModifier` context option.
*/
@property (nonatomic, strong, nullable) id<SDWebImageDownloaderRequestModifier> requestModifier;
/**
* Set the response modifier to modify the original download response during image load.
* This response modifier method will be called for each downloading image response. Return the original response means no modification. Return nil will mark current download as cancelled.
* Defaults to nil, means does not modify the original download response.
* @note If you want to modify single response, consider using `SDWebImageContextDownloadResponseModifier` context option.
*/
@property (nonatomic, strong, nullable) id<SDWebImageDownloaderResponseModifier> responseModifier;
/**
* Set the decryptor to decrypt the original download data before image decoding. This can be used for encrypted image data, like Base64.
* This decryptor method will be called for each downloading image data. Return the original data means no modification. Return nil will mark this download failed.
* Defaults to nil, means does not modify the original download data.
* @note When using decryptor, progressive decoding will be disabled, to avoid data corrupt issue.
* @note If you want to decrypt single download data, consider using `SDWebImageContextDownloadDecryptor` context option.
*/
@property (nonatomic, strong, nullable) id<SDWebImageDownloaderDecryptor> decryptor;
/**
* The configuration in use by the internal NSURLSession. If you want to provide a custom sessionConfiguration, use `SDWebImageDownloaderConfig.sessionConfiguration` and create a new downloader instance.
@note This is immutable according to NSURLSession's documentation. Mutating this object directly has no effect.
*/
@property (nonatomic, readonly, nonnull) NSURLSessionConfiguration *sessionConfiguration;
/**
* Gets/Sets the download queue suspension state.
*/
@property (nonatomic, assign, getter=isSuspended) BOOL suspended;
/**
* Shows the current amount of downloads that still need to be downloaded
*/
@property (nonatomic, assign, readonly) NSUInteger currentDownloadCount;
/**
* Returns the global shared downloader instance. Which use the `SDWebImageDownloaderConfig.defaultDownloaderConfig` config.
*/
@property (nonatomic, class, readonly, nonnull) SDWebImageDownloader *sharedDownloader;
/**
Creates an instance of a downloader with specified downloader config.
You can specify session configuration, timeout or operation class through downloader config.
@param config The downloader config. If you specify nil, the `defaultDownloaderConfig` will be used.
@return new instance of downloader class
*/
- (nonnull instancetype)initWithConfig:(nullable SDWebImageDownloaderConfig *)config NS_DESIGNATED_INITIALIZER;
/**
* 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 field.
* @param field The name of the header field to set.
*/
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable 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.
*/
- (nullable NSString *)valueForHTTPHeaderField:(nullable 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 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 token (SDWebImageDownloadToken) that can be used to cancel this operation
*/
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
/**
* 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
* @note the progress block is executed on a background queue
* @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 SDWebImageDownloaderProgressiveLoad isn't use. With the
* SDWebImageDownloaderProgressiveLoad 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 token (SDWebImageDownloadToken) that can be used to cancel this operation
*/
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
/**
* 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called repeatedly while the image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called once the download is completed.
*
* @return A token (SDWebImageDownloadToken) that can be used to cancel this operation
*/
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
/**
* Cancels all download operations in the queue
*/
- (void)cancelAllDownloads;
/**
* Invalidates the managed session, optionally canceling pending operations.
* @note If you use custom downloader instead of the shared downloader, you need call this method when you do not use it to avoid memory leak
* @param cancelPendingOperations Whether or not to cancel pending operations.
* @note Calling this method on the shared downloader has no effect.
*/
- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations;
@end
/**
SDWebImageDownloader is the built-in image loader conform to `SDImageLoader`. Which provide the HTTP/HTTPS/FTP download, or local file URL using NSURLSession.
However, this downloader class itself also support customization for advanced users. You can specify `operationClass` in download config to custom download operation, See `SDWebImageDownloaderOperation`.
If you want to provide some image loader which beyond network or local file, consider to create your own custom class conform to `SDImageLoader`.
*/
@interface SDWebImageDownloader (SDImageLoader) <SDImageLoader>
@end

View File

@@ -0,0 +1,665 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloader.h"
#import "SDWebImageDownloaderConfig.h"
#import "SDWebImageDownloaderOperation.h"
#import "SDWebImageError.h"
#import "SDWebImageCacheKeyFilter.h"
#import "SDImageCacheDefine.h"
#import "SDInternalMacros.h"
#import "objc/runtime.h"
NSNotificationName const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
NSNotificationName const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification";
NSNotificationName const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
NSNotificationName const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification";
static void * SDWebImageDownloaderContext = &SDWebImageDownloaderContext;
@interface SDWebImageDownloadToken ()
@property (nonatomic, strong, nullable, readwrite) NSURL *url;
@property (nonatomic, strong, nullable, readwrite) NSURLRequest *request;
@property (nonatomic, strong, nullable, readwrite) NSURLResponse *response;
@property (nonatomic, strong, nullable, readwrite) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
@property (nonatomic, weak, nullable, readwrite) id downloadOperationCancelToken;
@property (nonatomic, weak, nullable) NSOperation<SDWebImageDownloaderOperation> *downloadOperation;
@property (nonatomic, assign, getter=isCancelled) BOOL cancelled;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
- (nonnull instancetype)initWithDownloadOperation:(nullable NSOperation<SDWebImageDownloaderOperation> *)downloadOperation;
@end
@interface SDWebImageDownloader () <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue;
@property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, NSOperation<SDWebImageDownloaderOperation> *> *URLOperations;
@property (strong, nonatomic, nullable) NSMutableDictionary<NSString *, NSString *> *HTTPHeaders;
// The session in which data tasks will run
@property (strong, nonatomic) NSURLSession *session;
@end
@implementation SDWebImageDownloader {
SD_LOCK_DECLARE(_HTTPHeadersLock); // A lock to keep the access to `HTTPHeaders` thread-safe
SD_LOCK_DECLARE(_operationsLock); // A lock to keep the access to `URLOperations` thread-safe
}
+ (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];
}
}
+ (nonnull instancetype)sharedDownloader {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (nonnull instancetype)init {
return [self initWithConfig:SDWebImageDownloaderConfig.defaultDownloaderConfig];
}
- (instancetype)initWithConfig:(SDWebImageDownloaderConfig *)config {
self = [super init];
if (self) {
if (!config) {
config = SDWebImageDownloaderConfig.defaultDownloaderConfig;
}
_config = [config copy];
[_config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) options:0 context:SDWebImageDownloaderContext];
_downloadQueue = [NSOperationQueue new];
_downloadQueue.maxConcurrentOperationCount = _config.maxConcurrentDownloads;
_downloadQueue.name = @"com.hackemist.SDWebImageDownloader.downloadQueue";
_URLOperations = [NSMutableDictionary new];
NSMutableDictionary<NSString *, NSString *> *headerDictionary = [NSMutableDictionary dictionary];
NSString *userAgent = nil;
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
#if SD_VISION
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; visionOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], UITraitCollection.currentTraitCollection.displayScale];
#elif SD_UIKIT
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
#elif SD_WATCH
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]];
#elif SD_MAC
userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
#endif
if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
headerDictionary[@"User-Agent"] = userAgent;
}
headerDictionary[@"Accept"] = @"image/*,*/*;q=0.8";
_HTTPHeaders = headerDictionary;
SD_LOCK_INIT(_HTTPHeadersLock);
SD_LOCK_INIT(_operationsLock);
NSURLSessionConfiguration *sessionConfiguration = _config.sessionConfiguration;
if (!sessionConfiguration) {
sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
}
/**
* Create the session for this task
* We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate
* method calls and completion handler calls.
*/
_session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
}
return self;
}
- (void)dealloc {
[self.downloadQueue cancelAllOperations];
[self.config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) context:SDWebImageDownloaderContext];
// Invalide the URLSession after all operations been cancelled
[self.session invalidateAndCancel];
self.session = nil;
}
- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations {
if (self == [SDWebImageDownloader sharedDownloader]) {
return;
}
if (cancelPendingOperations) {
[self.session invalidateAndCancel];
} else {
[self.session finishTasksAndInvalidate];
}
}
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field {
if (!field) {
return;
}
SD_LOCK(_HTTPHeadersLock);
[self.HTTPHeaders setValue:value forKey:field];
SD_UNLOCK(_HTTPHeadersLock);
}
- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field {
if (!field) {
return nil;
}
SD_LOCK(_HTTPHeadersLock);
NSString *value = [self.HTTPHeaders objectForKey:field];
SD_UNLOCK(_HTTPHeadersLock);
return value;
}
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url
completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
return [self downloadImageWithURL:url options:0 progress:nil completed:completedBlock];
}
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
return [self downloadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock];
}
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
// 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) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}];
completedBlock(nil, nil, error, YES);
}
return nil;
}
id downloadOperationCancelToken;
// When different thumbnail size download with same url, we need to make sure each callback called with desired size
id<SDWebImageCacheKeyFilter> cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
NSString *cacheKey;
if (cacheKeyFilter) {
cacheKey = [cacheKeyFilter cacheKeyForURL:url];
} else {
cacheKey = url.absoluteString;
}
SDImageCoderOptions *decodeOptions = SDGetDecodeOptionsFromContext(context, [self.class imageOptionsFromDownloaderOptions:options], cacheKey);
SD_LOCK(_operationsLock);
NSOperation<SDWebImageDownloaderOperation> *operation = [self.URLOperations objectForKey:url];
// There is a case that the operation may be marked as finished or cancelled, but not been removed from `self.URLOperations`.
BOOL shouldNotReuseOperation;
if (operation) {
@synchronized (operation) {
shouldNotReuseOperation = operation.isFinished || operation.isCancelled;
}
} else {
shouldNotReuseOperation = YES;
}
if (shouldNotReuseOperation) {
operation = [self createDownloaderOperationWithUrl:url options:options context:context];
if (!operation) {
SD_UNLOCK(_operationsLock);
if (completedBlock) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Downloader operation is nil"}];
completedBlock(nil, nil, error, YES);
}
return nil;
}
@weakify(self);
operation.completionBlock = ^{
@strongify(self);
if (!self) {
return;
}
SD_LOCK(self->_operationsLock);
[self.URLOperations removeObjectForKey:url];
SD_UNLOCK(self->_operationsLock);
};
[self.URLOperations setObject:operation forKey:url];
// Add the handlers before submitting to operation queue, avoid the race condition that operation finished before setting handlers.
downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:decodeOptions];
// Add operation to operation queue only after all configuration done according to Apple's doc.
// `addOperation:` does not synchronously execute the `operation.completionBlock` so this will not cause deadlock.
[self.downloadQueue addOperation:operation];
} else {
// When we reuse the download operation to attach more callbacks, there may be thread safe issue because the getter of callbacks may in another queue (decoding queue or delegate queue)
// So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes.
@synchronized (operation) {
downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:decodeOptions];
}
}
SD_UNLOCK(_operationsLock);
SDWebImageDownloadToken *token = [[SDWebImageDownloadToken alloc] initWithDownloadOperation:operation];
token.url = url;
token.request = operation.request;
token.downloadOperationCancelToken = downloadOperationCancelToken;
return token;
}
#pragma mark Helper methods
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ (SDWebImageOptions)imageOptionsFromDownloaderOptions:(SDWebImageDownloaderOptions)downloadOptions {
SDWebImageOptions options = 0;
if (downloadOptions & SDWebImageDownloaderScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages;
if (downloadOptions & SDWebImageDownloaderDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly;
if (downloadOptions & SDWebImageDownloaderPreloadAllFrames) options |= SDWebImagePreloadAllFrames;
if (downloadOptions & SDWebImageDownloaderAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage;
if (downloadOptions & SDWebImageDownloaderMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass;
return options;
}
#pragma clang diagnostic pop
- (nullable NSOperation<SDWebImageDownloaderOperation> *)createDownloaderOperationWithUrl:(nonnull NSURL *)url
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context {
NSTimeInterval timeoutInterval = self.config.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
NSURLRequestCachePolicy cachePolicy = options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData;
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
mutableRequest.HTTPShouldHandleCookies = SD_OPTIONS_CONTAINS(options, SDWebImageDownloaderHandleCookies);
mutableRequest.HTTPShouldUsePipelining = YES;
SD_LOCK(_HTTPHeadersLock);
mutableRequest.allHTTPHeaderFields = self.HTTPHeaders;
SD_UNLOCK(_HTTPHeadersLock);
// Context Option
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
// Request Modifier
id<SDWebImageDownloaderRequestModifier> requestModifier;
if ([context valueForKey:SDWebImageContextDownloadRequestModifier]) {
requestModifier = [context valueForKey:SDWebImageContextDownloadRequestModifier];
} else {
requestModifier = self.requestModifier;
}
NSURLRequest *request;
if (requestModifier) {
NSURLRequest *modifiedRequest = [requestModifier modifiedRequestWithRequest:[mutableRequest copy]];
// If modified request is nil, early return
if (!modifiedRequest) {
return nil;
} else {
request = [modifiedRequest copy];
}
} else {
request = [mutableRequest copy];
}
// Response Modifier
id<SDWebImageDownloaderResponseModifier> responseModifier;
if ([context valueForKey:SDWebImageContextDownloadResponseModifier]) {
responseModifier = [context valueForKey:SDWebImageContextDownloadResponseModifier];
} else {
responseModifier = self.responseModifier;
}
if (responseModifier) {
mutableContext[SDWebImageContextDownloadResponseModifier] = responseModifier;
}
// Decryptor
id<SDWebImageDownloaderDecryptor> decryptor;
if ([context valueForKey:SDWebImageContextDownloadDecryptor]) {
decryptor = [context valueForKey:SDWebImageContextDownloadDecryptor];
} else {
decryptor = self.decryptor;
}
if (decryptor) {
mutableContext[SDWebImageContextDownloadDecryptor] = decryptor;
}
context = [mutableContext copy];
// Operation Class
Class operationClass = self.config.operationClass;
if (!operationClass) {
operationClass = [SDWebImageDownloaderOperation class];
}
NSOperation<SDWebImageDownloaderOperation> *operation = [[operationClass alloc] initWithRequest:request inSession:self.session options:options context:context];
if ([operation respondsToSelector:@selector(setCredential:)]) {
if (self.config.urlCredential) {
operation.credential = self.config.urlCredential;
} else if (self.config.username && self.config.password) {
operation.credential = [NSURLCredential credentialWithUser:self.config.username password:self.config.password persistence:NSURLCredentialPersistenceForSession];
}
}
if ([operation respondsToSelector:@selector(setMinimumProgressInterval:)]) {
operation.minimumProgressInterval = MIN(MAX(self.config.minimumProgressInterval, 0), 1);
}
if ([operation respondsToSelector:@selector(setAcceptableStatusCodes:)]) {
operation.acceptableStatusCodes = self.config.acceptableStatusCodes;
}
if ([operation respondsToSelector:@selector(setAcceptableContentTypes:)]) {
operation.acceptableContentTypes = self.config.acceptableContentTypes;
}
if (options & SDWebImageDownloaderHighPriority) {
operation.queuePriority = NSOperationQueuePriorityHigh;
} else if (options & SDWebImageDownloaderLowPriority) {
operation.queuePriority = NSOperationQueuePriorityLow;
}
if (self.config.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
// Emulate LIFO execution order by systematically, each previous adding operation can dependency the new operation
// This can gurantee the new operation to be execulated firstly, even if when some operations finished, meanwhile you appending new operations
// Just make last added operation dependents new operation can not solve this problem. See test case #test15DownloaderLIFOExecutionOrder
for (NSOperation *pendingOperation in self.downloadQueue.operations) {
[pendingOperation addDependency:operation];
}
}
return operation;
}
- (void)cancelAllDownloads {
[self.downloadQueue cancelAllOperations];
}
#pragma mark - Properties
- (BOOL)isSuspended {
return self.downloadQueue.isSuspended;
}
- (void)setSuspended:(BOOL)suspended {
self.downloadQueue.suspended = suspended;
}
- (NSUInteger)currentDownloadCount {
return self.downloadQueue.operationCount;
}
- (NSURLSessionConfiguration *)sessionConfiguration {
return self.session.configuration;
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (context == SDWebImageDownloaderContext) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxConcurrentDownloads))]) {
self.downloadQueue.maxConcurrentOperationCount = self.config.maxConcurrentDownloads;
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark Helper methods
- (NSOperation<SDWebImageDownloaderOperation> *)operationWithTask:(NSURLSessionTask *)task {
NSOperation<SDWebImageDownloaderOperation> *returnOperation = nil;
for (NSOperation<SDWebImageDownloaderOperation> *operation in self.downloadQueue.operations) {
if ([operation respondsToSelector:@selector(dataTask)]) {
// So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes.
NSURLSessionTask *operationTask;
@synchronized (operation) {
operationTask = operation.dataTask;
}
if (operationTask.taskIdentifier == task.taskIdentifier) {
returnOperation = operation;
break;
}
}
}
return returnOperation;
}
#pragma mark NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:dataTask];
if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveResponse:completionHandler:)]) {
[dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler];
} else {
if (completionHandler) {
completionHandler(NSURLSessionResponseAllow);
}
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:dataTask];
if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)]) {
[dataOperation URLSession:session dataTask:dataTask didReceiveData:data];
}
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:dataTask];
if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:willCacheResponse:completionHandler:)]) {
[dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler];
} else {
if (completionHandler) {
completionHandler(proposedResponse);
}
}
}
#pragma mark NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:task];
if ([dataOperation respondsToSelector:@selector(URLSession:task:didCompleteWithError:)]) {
[dataOperation URLSession:session task:task didCompleteWithError:error];
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:task];
if ([dataOperation respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) {
[dataOperation URLSession:session task:task willPerformHTTPRedirection:response newRequest:request completionHandler:completionHandler];
} else {
if (completionHandler) {
completionHandler(request);
}
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:task];
if ([dataOperation respondsToSelector:@selector(URLSession:task:didReceiveChallenge:completionHandler:)]) {
[dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler];
} else {
if (completionHandler) {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)) {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:task];
if ([dataOperation respondsToSelector:@selector(URLSession:task:didFinishCollectingMetrics:)]) {
[dataOperation URLSession:session task:task didFinishCollectingMetrics:metrics];
}
}
@end
@implementation SDWebImageDownloadToken
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:SDWebImageDownloadReceiveResponseNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:SDWebImageDownloadStopNotification object:nil];
}
- (instancetype)initWithDownloadOperation:(NSOperation<SDWebImageDownloaderOperation> *)downloadOperation {
self = [super init];
if (self) {
_downloadOperation = downloadOperation;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadDidReceiveResponse:) name:SDWebImageDownloadReceiveResponseNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadDidStop:) name:SDWebImageDownloadStopNotification object:nil];
}
return self;
}
- (void)downloadDidReceiveResponse:(NSNotification *)notification {
NSOperation<SDWebImageDownloaderOperation> *downloadOperation = notification.object;
if (downloadOperation && downloadOperation == self.downloadOperation) {
self.response = downloadOperation.response;
}
}
- (void)downloadDidStop:(NSNotification *)notification {
NSOperation<SDWebImageDownloaderOperation> *downloadOperation = notification.object;
if (downloadOperation && downloadOperation == self.downloadOperation) {
if ([downloadOperation respondsToSelector:@selector(metrics)]) {
if (@available(iOS 10.0, tvOS 10.0, macOS 10.12, watchOS 3.0, *)) {
self.metrics = downloadOperation.metrics;
}
}
}
}
- (void)cancel {
@synchronized (self) {
if (self.isCancelled) {
return;
}
self.cancelled = YES;
[self.downloadOperation cancel:self.downloadOperationCancelToken];
self.downloadOperationCancelToken = nil;
}
}
@end
@implementation SDWebImageDownloader (SDImageLoader)
- (BOOL)canRequestImageForURL:(NSURL *)url {
return [self canRequestImageForURL:url options:0 context:nil];
}
- (BOOL)canRequestImageForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
if (!url) {
return NO;
}
// Always pass YES to let URLSession or custom download operation to determine
return YES;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (id<SDWebImageOperation>)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock {
UIImage *cachedImage = context[SDWebImageContextLoaderCachedImage];
SDWebImageDownloaderOptions downloaderOptions = 0;
if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
if (options & SDWebImageProgressiveLoad) downloaderOptions |= SDWebImageDownloaderProgressiveLoad;
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 (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages;
if (options & SDWebImageAvoidDecodeImage) downloaderOptions |= SDWebImageDownloaderAvoidDecodeImage;
if (options & SDWebImageDecodeFirstFrameOnly) downloaderOptions |= SDWebImageDownloaderDecodeFirstFrameOnly;
if (options & SDWebImagePreloadAllFrames) downloaderOptions |= SDWebImageDownloaderPreloadAllFrames;
if (options & SDWebImageMatchAnimatedImageClass) downloaderOptions |= SDWebImageDownloaderMatchAnimatedImageClass;
if (cachedImage && options & SDWebImageRefreshCached) {
// force progressive off if image already cached but forced refreshing
downloaderOptions &= ~SDWebImageDownloaderProgressiveLoad;
// ignore image read from NSURLCache if image if cached but force refreshing
downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
}
return [self downloadImageWithURL:url options:downloaderOptions context:context progress:progressBlock completed:completedBlock];
}
#pragma clang diagnostic pop
- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error {
return [self shouldBlockFailedURLWithURL:url error:error options:0 context:nil];
}
- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
BOOL shouldBlockFailedURL;
// Filter the error domain and check error codes
if ([error.domain isEqualToString:SDWebImageErrorDomain]) {
shouldBlockFailedURL = ( error.code == SDWebImageErrorInvalidURL
|| error.code == SDWebImageErrorBadImageData);
} else if ([error.domain isEqualToString:NSURLErrorDomain]) {
shouldBlockFailedURL = ( error.code != NSURLErrorNotConnectedToInternet
&& error.code != NSURLErrorCancelled
&& error.code != NSURLErrorTimedOut
&& error.code != NSURLErrorInternationalRoamingOff
&& error.code != NSURLErrorDataNotAllowed
&& error.code != NSURLErrorCannotFindHost
&& error.code != NSURLErrorCannotConnectToHost
&& error.code != NSURLErrorNetworkConnectionLost);
} else {
shouldBlockFailedURL = NO;
}
return shouldBlockFailedURL;
}
@end

View File

@@ -0,0 +1,113 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
/// Operation execution order
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
};
/**
The class contains all the config for image downloader
@note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well.
*/
@interface SDWebImageDownloaderConfig : NSObject <NSCopying>
/**
Gets the default downloader config used for shared instance or initialization when it does not provide any downloader config. Such as `SDWebImageDownloader.sharedDownloader`.
@note You can modify the property on default downloader config, which can be used for later created downloader instance. The already created downloader instance does not get affected.
*/
@property (nonatomic, class, readonly, nonnull) SDWebImageDownloaderConfig *defaultDownloaderConfig;
/**
* The maximum number of concurrent downloads.
* Defaults to 6.
*/
@property (nonatomic, assign) NSInteger maxConcurrentDownloads;
/**
* The timeout value (in seconds) for each download operation.
* Defaults to 15.0.
*/
@property (nonatomic, assign) NSTimeInterval downloadTimeout;
/**
* The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected.
* The value should be 0.0-1.0.
* @note If you're using progressive decoding feature, this will also effect the image refresh rate.
* @note This value may enhance the performance if you don't want progress callback too frequently.
* Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately.
*/
@property (nonatomic, assign) double minimumProgressInterval;
/**
* The custom session configuration in use by NSURLSession. If you don't provide one, we will use `defaultSessionConfiguration` instead.
* Defatuls to nil.
* @note This property does not support dynamic changes, means it's immutable after the downloader instance initialized.
*/
@property (nonatomic, strong, nullable) NSURLSessionConfiguration *sessionConfiguration;
/**
* Gets/Sets a subclass of `SDWebImageDownloaderOperation` as the default
* `NSOperation` to be used each time SDWebImage constructs a request
* operation to download an image.
* Defaults to nil.
* @note Passing `NSOperation<SDWebImageDownloaderOperation>` to set as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`.
*/
@property (nonatomic, assign, nullable) Class operationClass;
/**
* Changes download operations execution order.
* Defaults to `SDWebImageDownloaderFIFOExecutionOrder`.
*/
@property (nonatomic, assign) SDWebImageDownloaderExecutionOrder executionOrder;
/**
* Set the default URL credential to be set for request operations.
* Defaults to nil.
*/
@property (nonatomic, copy, nullable) NSURLCredential *urlCredential;
/**
* Set username using for HTTP Basic authentication.
* Defaults to nil.
*/
@property (nonatomic, copy, nullable) NSString *username;
/**
* Set password using for HTTP Basic authentication.
* Defaults to nil.
*/
@property (nonatomic, copy, nullable) NSString *password;
/**
* Set the acceptable HTTP Response status code. The status code which beyond the range will mark the download operation failed.
* For example, if we config [200, 400) but server response is 503, the download will fail with error code `SDWebImageErrorInvalidDownloadStatusCode`.
* Defaults to [200,400). Nil means no validation at all.
*/
@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
/**
* Set the acceptable HTTP Response content type. The content type beyond the set will mark the download operation failed.
* For example, if we config ["image/png"] but server response is "application/json", the download will fail with error code `SDWebImageErrorInvalidDownloadContentType`.
* Normally you don't need this for image format detection because we use image's data file signature magic bytes: https://en.wikipedia.org/wiki/List_of_file_signatures
* Defaults to nil. Nil means no validation at all.
*/
@property (nonatomic, copy, nullable) NSSet<NSString *> *acceptableContentTypes;
@end

View File

@@ -0,0 +1,60 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderConfig.h"
#import "SDWebImageDownloaderOperation.h"
static SDWebImageDownloaderConfig * _defaultDownloaderConfig;
@implementation SDWebImageDownloaderConfig
+ (SDWebImageDownloaderConfig *)defaultDownloaderConfig {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_defaultDownloaderConfig = [SDWebImageDownloaderConfig new];
});
return _defaultDownloaderConfig;
}
- (instancetype)init {
self = [super init];
if (self) {
_maxConcurrentDownloads = 6;
_downloadTimeout = 15.0;
_executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
_acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
SDWebImageDownloaderConfig *config = [[[self class] allocWithZone:zone] init];
config.maxConcurrentDownloads = self.maxConcurrentDownloads;
config.downloadTimeout = self.downloadTimeout;
config.minimumProgressInterval = self.minimumProgressInterval;
config.sessionConfiguration = [self.sessionConfiguration copyWithZone:zone];
config.operationClass = self.operationClass;
config.executionOrder = self.executionOrder;
config.urlCredential = self.urlCredential;
config.username = self.username;
config.password = self.password;
config.acceptableStatusCodes = self.acceptableStatusCodes;
config.acceptableContentTypes = self.acceptableContentTypes;
return config;
}
- (void)setOperationClass:(Class)operationClass {
if (operationClass) {
NSAssert([operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperation)], @"Custom downloader operation class must subclass NSOperation and conform to `SDWebImageDownloaderOperation` protocol");
}
_operationClass = operationClass;
}
@end

View File

@@ -0,0 +1,52 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
typedef NSData * _Nullable (^SDWebImageDownloaderDecryptorBlock)(NSData * _Nonnull data, NSURLResponse * _Nullable response);
/**
This is the protocol for downloader decryptor. Which decrypt the original encrypted data before decoding. Note progressive decoding is not compatible for decryptor.
We can use a block to specify the downloader decryptor. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options.
*/
@protocol SDWebImageDownloaderDecryptor <NSObject>
/// Decrypt the original download data and return a new data. You can use this to decrypt the data using your preferred algorithm.
/// @param data The original download data
/// @param response The URL response for data. If you modify the original URL response via response modifier, the modified version will be here. This arg is nullable.
/// @note If nil is returned, the image download will be marked as failed with error `SDWebImageErrorBadImageData`
- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response;
@end
/**
A downloader response modifier class with block.
*/
@interface SDWebImageDownloaderDecryptor : NSObject <SDWebImageDownloaderDecryptor>
/// Create the data decryptor with block
/// @param block A block to control decrypt logic
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block;
/// Create the data decryptor with block
/// @param block A block to control decrypt logic
+ (nonnull instancetype)decryptorWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end
/// Convenience way to create decryptor for common data encryption.
@interface SDWebImageDownloaderDecryptor (Conveniences)
/// Base64 Encoded image data decryptor
@property (class, readonly, nonnull) SDWebImageDownloaderDecryptor *base64Decryptor;
@end

View File

@@ -0,0 +1,55 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderDecryptor.h"
@interface SDWebImageDownloaderDecryptor ()
@property (nonatomic, copy, nonnull) SDWebImageDownloaderDecryptorBlock block;
@end
@implementation SDWebImageDownloaderDecryptor
- (instancetype)initWithBlock:(SDWebImageDownloaderDecryptorBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)decryptorWithBlock:(SDWebImageDownloaderDecryptorBlock)block {
SDWebImageDownloaderDecryptor *decryptor = [[SDWebImageDownloaderDecryptor alloc] initWithBlock:block];
return decryptor;
}
- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response {
if (!self.block) {
return nil;
}
return self.block(data, response);
}
@end
@implementation SDWebImageDownloaderDecryptor (Conveniences)
+ (SDWebImageDownloaderDecryptor *)base64Decryptor {
static SDWebImageDownloaderDecryptor *decryptor;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
decryptor = [SDWebImageDownloaderDecryptor decryptorWithBlock:^NSData * _Nullable(NSData * _Nonnull data, NSURLResponse * _Nullable response) {
NSData *modifiedData = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters];
return modifiedData;
}];
});
return decryptor;
}
@end

View File

@@ -0,0 +1,191 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageDownloader.h"
#import "SDWebImageOperation.h"
/**
Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol
For the description about these methods, see `SDWebImageDownloaderOperation`
@note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods.
*/
@protocol SDWebImageDownloaderOperation <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@required
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options;
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context;
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock
decodeOptions:(nullable SDImageCoderOptions *)decodeOptions;
- (BOOL)cancel:(nullable id)token;
@property (strong, nonatomic, readonly, nullable) NSURLRequest *request;
@property (strong, nonatomic, readonly, nullable) NSURLResponse *response;
@optional
@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask;
@property (strong, nonatomic, readonly, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
// These operation-level config was inherited from downloader. See `SDWebImageDownloaderConfig` for documentation.
@property (strong, nonatomic, nullable) NSURLCredential *credential;
@property (assign, nonatomic) double minimumProgressInterval;
@property (copy, nonatomic, nullable) NSIndexSet *acceptableStatusCodes;
@property (copy, nonatomic, nullable) NSSet<NSString *> *acceptableContentTypes;
@end
/**
The download operation class for SDWebImageDownloader.
*/
@interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperation>
/**
* The request used by the operation's task.
*/
@property (strong, nonatomic, readonly, nullable) NSURLRequest *request;
/**
* The response returned by the operation's task.
*/
@property (strong, nonatomic, readonly, nullable) NSURLResponse *response;
/**
* The operation's task
*/
@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask;
/**
* The collected metrics from `-URLSession:task:didFinishCollectingMetrics:`.
* This can be used to collect the network metrics like download duration, DNS lookup duration, SSL handshake duration, etc. See Apple's documentation: https://developer.apple.com/documentation/foundation/urlsessiontaskmetrics
*/
@property (strong, nonatomic, readonly, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
/**
* The credential used for authentication challenges in `-URLSession:task:didReceiveChallenge:completionHandler:`.
*
* This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
*/
@property (strong, nonatomic, nullable) NSURLCredential *credential;
/**
* The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected.
* The value should be 0.0-1.0.
* @note If you're using progressive decoding feature, this will also effect the image refresh rate.
* @note This value may enhance the performance if you don't want progress callback too frequently.
* Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately.
*/
@property (assign, nonatomic) double minimumProgressInterval;
/**
* Set the acceptable HTTP Response status code. The status code which beyond the range will mark the download operation failed.
* For example, if we config [200, 400) but server response is 503, the download will fail with error code `SDWebImageErrorInvalidDownloadStatusCode`.
* Defaults to [200,400). Nil means no validation at all.
*/
@property (copy, nonatomic, nullable) NSIndexSet *acceptableStatusCodes;
/**
* Set the acceptable HTTP Response content type. The content type beyond the set will mark the download operation failed.
* For example, if we config ["image/png"] but server response is "application/json", the download will fail with error code `SDWebImageErrorInvalidDownloadContentType`.
* Normally you don't need this for image format detection because we use image's data file signature magic bytes: https://en.wikipedia.org/wiki/List_of_file_signatures
* Defaults to nil. Nil means no validation at all.
*/
@property (copy, nonatomic, nullable) NSSet<NSString *> *acceptableContentTypes;
/**
* The options for the receiver.
*/
@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
/**
* The context for the receiver.
*/
@property (copy, nonatomic, readonly, nullable) SDWebImageContext *context;
/**
* Initializes a `SDWebImageDownloaderOperation` object
*
* @see SDWebImageDownloaderOperation
*
* @param request the URL request
* @param session the URL session in which this operation will run
* @param options downloader options
*
* @return the initialized instance
*/
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options;
/**
* Initializes a `SDWebImageDownloaderOperation` object
*
* @see SDWebImageDownloaderOperation
*
* @param request the URL request
* @param session the URL session in which this operation will run
* @param options downloader options
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*
* @return the initialized instance
*/
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context NS_DESIGNATED_INITIALIZER;
/**
* Adds handlers for progress and completion. Returns a token that can be passed to -cancel: to cancel this set of
* callbacks.
*
* @param progressBlock the block executed when a new chunk of data arrives.
* @note the progress block is executed on a background queue
* @param completedBlock the block executed when the download is done.
* @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
*
* @return the token to use to cancel this set of handlers
*/
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
/**
* Adds handlers for progress and completion, and optional decode options (which need another image other than the initial one). Returns a token that can be passed to -cancel: to cancel this set of
* callbacks.
*
* @param progressBlock the block executed when a new chunk of data arrives.
* @note the progress block is executed on a background queue
* @param completedBlock the block executed when the download is done.
* @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
* @param decodeOptions The optional decode options, used when in thumbnail decoding for current completion block callback. For example, request <url1, {thumbnail: 100x100}> and then <url1, {thumbnail: 200x200}>, we may callback these two completion block with different size.
* @return the token to use to cancel this set of handlers
*/
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock
decodeOptions:(nullable SDImageCoderOptions *)decodeOptions;
/**
* Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled.
*
* @param token the token representing a set of callbacks to cancel
*
* @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise.
*/
- (BOOL)cancel:(nullable id)token;
@end

View File

@@ -0,0 +1,760 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderOperation.h"
#import "SDWebImageError.h"
#import "SDInternalMacros.h"
#import "SDWebImageDownloaderResponseModifier.h"
#import "SDWebImageDownloaderDecryptor.h"
#import "SDImageCacheDefine.h"
#import "SDCallbackQueue.h"
// A handler to represent individual request
@interface SDWebImageDownloaderOperationToken : NSObject
@property (nonatomic, copy, nullable) SDWebImageDownloaderCompletedBlock completedBlock;
@property (nonatomic, copy, nullable) SDWebImageDownloaderProgressBlock progressBlock;
@property (nonatomic, copy, nullable) SDImageCoderOptions *decodeOptions;
@end
@implementation SDWebImageDownloaderOperationToken
- (BOOL)isEqual:(id)other {
if (nil == other) {
return NO;
}
if (self == other) {
return YES;
}
if (![other isKindOfClass:[self class]]) {
return NO;
}
SDWebImageDownloaderOperationToken *object = (SDWebImageDownloaderOperationToken *)other;
// warn: only compare decodeOptions, ignore pointer, use `removeObjectIdenticalTo`
BOOL result = [self.decodeOptions isEqualToDictionary:object.decodeOptions];
return result;
}
@end
@interface SDWebImageDownloaderOperation ()
@property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageDownloaderOperationToken *> *callbackTokens;
@property (assign, nonatomic, readwrite) SDWebImageDownloaderOptions options;
@property (copy, nonatomic, readwrite, nullable) SDWebImageContext *context;
@property (assign, nonatomic, getter = isExecuting) BOOL executing;
@property (assign, nonatomic, getter = isFinished) BOOL finished;
@property (strong, nonatomic, nullable) NSMutableData *imageData;
@property (copy, nonatomic, nullable) NSData *cachedData; // for `SDWebImageDownloaderIgnoreCachedResponse`
@property (assign, nonatomic) NSUInteger expectedSize; // may be 0
@property (assign, nonatomic) NSUInteger receivedSize;
@property (strong, nonatomic, nullable, readwrite) NSURLResponse *response;
@property (strong, nonatomic, nullable) NSError *responseError;
@property (assign, nonatomic) double previousProgress; // previous progress percent
@property (assign, nonatomic, getter = isDownloadCompleted) BOOL downloadCompleted;
@property (strong, nonatomic, nullable) id<SDWebImageDownloaderResponseModifier> responseModifier; // modify original URLResponse
@property (strong, nonatomic, nullable) id<SDWebImageDownloaderDecryptor> decryptor; // decrypt image data
// This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won't be able to run
// the task associated with this operation
@property (weak, nonatomic, nullable) NSURLSession *unownedSession;
// This is set if we're using not using an injected NSURLSession. We're responsible of invalidating this one
@property (strong, nonatomic, nullable) NSURLSession *ownedSession;
@property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask;
@property (strong, nonatomic, readwrite, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
@property (strong, nonatomic, nonnull) NSOperationQueue *coderQueue; // the serial operation queue to do image decoding
@property (strong, nonatomic, nonnull) NSMapTable<SDImageCoderOptions *, UIImage *> *imageMap; // each variant of image is weak-referenced to avoid too many re-decode during downloading
#if SD_UIKIT
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
#endif
@end
@implementation SDWebImageDownloaderOperation
@synthesize executing = _executing;
@synthesize finished = _finished;
- (nonnull instancetype)init {
return [self initWithRequest:nil inSession:nil options:0];
}
- (instancetype)initWithRequest:(NSURLRequest *)request inSession:(NSURLSession *)session options:(SDWebImageDownloaderOptions)options {
return [self initWithRequest:request inSession:session options:options context:nil];
}
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options
context:(nullable SDWebImageContext *)context {
if ((self = [super init])) {
_request = [request copy];
_options = options;
_context = [context copy];
_callbackTokens = [NSMutableArray new];
_responseModifier = context[SDWebImageContextDownloadResponseModifier];
_decryptor = context[SDWebImageContextDownloadDecryptor];
_executing = NO;
_finished = NO;
_expectedSize = 0;
_unownedSession = session;
_downloadCompleted = NO;
_coderQueue = [[NSOperationQueue alloc] init];
_coderQueue.maxConcurrentOperationCount = 1;
_coderQueue.name = @"com.hackemist.SDWebImageDownloaderOperation.coderQueue";
_imageMap = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:1];
#if SD_UIKIT
_backgroundTaskId = UIBackgroundTaskInvalid;
#endif
}
return self;
}
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
return [self addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:nil];
}
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock
decodeOptions:(nullable SDImageCoderOptions *)decodeOptions {
if (!completedBlock && !progressBlock && !decodeOptions) return nil;
SDWebImageDownloaderOperationToken *token = [SDWebImageDownloaderOperationToken new];
token.completedBlock = completedBlock;
token.progressBlock = progressBlock;
token.decodeOptions = decodeOptions;
@synchronized (self) {
[self.callbackTokens addObject:token];
}
return token;
}
- (BOOL)cancel:(nullable id)token {
if (![token isKindOfClass:SDWebImageDownloaderOperationToken.class]) return NO;
BOOL shouldCancel = NO;
@synchronized (self) {
NSArray *tokens = self.callbackTokens;
if (tokens.count == 1 && [tokens indexOfObjectIdenticalTo:token] != NSNotFound) {
shouldCancel = YES;
}
}
if (shouldCancel) {
// Cancel operation running and callback last token's completion block
[self cancel];
} else {
// Only callback this token's completion block
@synchronized (self) {
[self.callbackTokens removeObjectIdenticalTo:token];
}
[self callCompletionBlockWithToken:token image:nil imageData:nil error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] finished:YES];
}
return shouldCancel;
}
- (void)start {
@synchronized (self) {
if (self.isCancelled) {
if (!self.isFinished) self.finished = YES;
// Operation cancelled by user before sending the request
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user before sending the request"}]];
[self reset];
return;
}
#if SD_UIKIT
Class UIApplicationClass = NSClassFromString(@"UIApplication");
BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)];
if (hasApplication && [self shouldContinueWhenAppEntersBackground]) {
__weak typeof(self) wself = self;
UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)];
self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
[wself cancel];
}];
}
#endif
NSURLSession *session = self.unownedSession;
if (!session) {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 15;
/**
* Create the session for this task
* We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate
* method calls and completion handler calls.
*/
session = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
self.ownedSession = session;
}
if (self.options & SDWebImageDownloaderIgnoreCachedResponse) {
// Grab the cached data for later check
NSURLCache *URLCache = session.configuration.URLCache;
if (!URLCache) {
URLCache = [NSURLCache sharedURLCache];
}
NSCachedURLResponse *cachedResponse;
// NSURLCache's `cachedResponseForRequest:` is not thread-safe, see https://developer.apple.com/documentation/foundation/nsurlcache#2317483
@synchronized (URLCache) {
cachedResponse = [URLCache cachedResponseForRequest:self.request];
}
if (cachedResponse) {
self.cachedData = cachedResponse.data;
self.response = cachedResponse.response;
}
}
if (!session.delegate) {
// Session been invalid and has no delegate at all
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Session delegate is nil and invalid"}]];
[self reset];
return;
}
self.dataTask = [session dataTaskWithRequest:self.request];
self.executing = YES;
}
if (self.dataTask) {
if (self.options & SDWebImageDownloaderHighPriority) {
self.dataTask.priority = NSURLSessionTaskPriorityHigh;
} else if (self.options & SDWebImageDownloaderLowPriority) {
self.dataTask.priority = NSURLSessionTaskPriorityLow;
} else {
self.dataTask.priority = NSURLSessionTaskPriorityDefault;
}
[self.dataTask resume];
NSArray<SDWebImageDownloaderOperationToken *> *tokens;
@synchronized (self) {
tokens = [self.callbackTokens copy];
}
for (SDWebImageDownloaderOperationToken *token in tokens) {
if (token.progressBlock) {
token.progressBlock(0, NSURLResponseUnknownLength, self.request.URL);
}
}
__block typeof(self) strongSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:strongSelf];
});
} else {
if (!self.isFinished) self.finished = YES;
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Task can't be initialized"}]];
[self reset];
}
}
- (void)cancel {
@synchronized (self) {
[self cancelInternal];
}
}
- (void)cancelInternal {
if (self.isFinished) return;
[super cancel];
__block typeof(self) strongSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf];
});
if (self.dataTask) {
// Cancel the URLSession, `URLSession:task:didCompleteWithError:` delegate callback will be ignored
[self.dataTask cancel];
self.dataTask = nil;
}
// NSOperation disallow setFinished=YES **before** operation's start method been called
// We check for the initialized status, which is isExecuting == NO && isFinished = NO
// Ony update for non-intialized status, which is !(isExecuting == NO && isFinished = NO), or if (self.isExecuting || self.isFinished) {...}
if (self.isExecuting || self.isFinished) {
if (self.isExecuting) self.executing = NO;
if (!self.isFinished) self.finished = YES;
}
// Operation cancelled by user during sending the request
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}]];
[self reset];
}
- (void)done {
self.finished = YES;
self.executing = NO;
[self reset];
}
- (void)reset {
@synchronized (self) {
[self.callbackTokens removeAllObjects];
self.dataTask = nil;
if (self.ownedSession) {
[self.ownedSession invalidateAndCancel];
self.ownedSession = nil;
}
#if SD_UIKIT
if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
// If backgroundTaskId != UIBackgroundTaskInvalid, sharedApplication is always exist
UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)];
[app endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = UIBackgroundTaskInvalid;
}
#endif
}
}
- (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)isAsynchronous {
return YES;
}
// Check for unprocessed tokens.
// if all tokens have been processed call [self done].
- (void)checkDoneWithImageData:(NSData *)imageData
finishedTokens:(NSArray<SDWebImageDownloaderOperationToken *> *)finishedTokens {
@synchronized (self) {
NSMutableArray<SDWebImageDownloaderOperationToken *> *tokens = [self.callbackTokens mutableCopy];
[finishedTokens enumerateObjectsUsingBlock:^(SDWebImageDownloaderOperationToken * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[tokens removeObjectIdenticalTo:obj];
}];
if (tokens.count == 0) {
[self done];
} else {
// If there are new tokens added during the decoding operation, the decoding operation is supplemented with these new tokens.
[self startCoderOperationWithImageData:imageData pendingTokens:tokens finishedTokens:finishedTokens];
}
}
}
- (void)startCoderOperationWithImageData:(NSData *)imageData
pendingTokens:(NSArray<SDWebImageDownloaderOperationToken *> *)pendingTokens
finishedTokens:(NSArray<SDWebImageDownloaderOperationToken *> *)finishedTokens {
@weakify(self);
for (SDWebImageDownloaderOperationToken *token in pendingTokens) {
[self.coderQueue addOperationWithBlock:^{
@strongify(self);
if (!self) {
return;
}
UIImage *image;
// check if we already decode this variant of image for current callback
if (token.decodeOptions) {
image = [self.imageMap objectForKey:token.decodeOptions];
}
if (!image) {
// check if we already use progressive decoding, use that to produce faster decoding
id<SDProgressiveImageCoder> progressiveCoder = SDImageLoaderGetProgressiveCoder(self);
SDWebImageOptions options = [[self class] imageOptionsFromDownloaderOptions:self.options];
SDWebImageContext *context;
if (token.decodeOptions) {
SDWebImageMutableContext *mutableContext = [NSMutableDictionary dictionaryWithDictionary:self.context];
SDSetDecodeOptionsToContext(mutableContext, &options, token.decodeOptions);
context = [mutableContext copy];
} else {
context = self.context;
}
if (progressiveCoder) {
image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, YES, self, options, context);
} else {
image = SDImageLoaderDecodeImageData(imageData, self.request.URL, options, context);
}
if (image && token.decodeOptions) {
[self.imageMap setObject:image forKey:token.decodeOptions];
}
}
CGSize imageSize = image.size;
if (imageSize.width == 0 || imageSize.height == 0) {
NSString *description = image == nil ? @"Downloaded image decode failed" : @"Downloaded image has 0 pixels";
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : description}];
[self callCompletionBlockWithToken:token image:nil imageData:nil error:error finished:YES];
} else {
[self callCompletionBlockWithToken:token image:image imageData:imageData error:nil finished:YES];
}
}];
}
// call [self done] after all completed block was dispatched
dispatch_block_t doneBlock = ^{
@strongify(self);
if (!self) {
return;
}
// Check for new tokens added during the decode operation.
[self checkDoneWithImageData:imageData
finishedTokens:[finishedTokens arrayByAddingObjectsFromArray:pendingTokens]];
};
if (@available(iOS 13, tvOS 13, macOS 10.15, watchOS 6, *)) {
// seems faster than `addOperationWithBlock`
[self.coderQueue addBarrierBlock:doneBlock];
} else {
// serial queue, this does the same effect in semantics
[self.coderQueue addOperationWithBlock:doneBlock];
}
}
#pragma mark NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
// Check response modifier, if return nil, will marked as cancelled.
BOOL valid = YES;
if (self.responseModifier && response) {
response = [self.responseModifier modifiedResponseWithResponse:response];
if (!response) {
valid = NO;
self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain
code:SDWebImageErrorInvalidDownloadResponse
userInfo:@{NSLocalizedDescriptionKey : @"Download marked as failed because response is nil"}];
}
}
NSInteger expected = (NSInteger)response.expectedContentLength;
expected = expected > 0 ? expected : 0;
self.expectedSize = expected;
self.response = response;
// Check status code valid (defaults [200,400))
NSInteger statusCode = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
BOOL statusCodeValid = YES;
if (valid && statusCode > 0 && self.acceptableStatusCodes) {
statusCodeValid = [self.acceptableStatusCodes containsIndex:statusCode];
}
if (!statusCodeValid) {
valid = NO;
self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain
code:SDWebImageErrorInvalidDownloadStatusCode
userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Download marked as failed because of invalid response status code %ld", (long)statusCode],
SDWebImageErrorDownloadStatusCodeKey : @(statusCode),
SDWebImageErrorDownloadResponseKey : response}];
}
// Check content type valid (defaults nil)
NSString *contentType = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).MIMEType : nil;
BOOL contentTypeValid = YES;
if (valid && contentType.length > 0 && self.acceptableContentTypes) {
contentTypeValid = [self.acceptableContentTypes containsObject:contentType];
}
if (!contentTypeValid) {
valid = NO;
self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain
code:SDWebImageErrorInvalidDownloadContentType
userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Download marked as failed because of invalid response content type %@", contentType],
SDWebImageErrorDownloadContentTypeKey : contentType,
SDWebImageErrorDownloadResponseKey : response}];
}
//'304 Not Modified' is an exceptional one
//URLSession current behavior will return 200 status code when the server respond 304 and URLCache hit. But this is not a standard behavior and we just add a check
if (valid && statusCode == 304 && !self.cachedData) {
valid = NO;
self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain
code:SDWebImageErrorCacheNotModified
userInfo:@{NSLocalizedDescriptionKey: @"Download response status code is 304 not modified and ignored",
SDWebImageErrorDownloadResponseKey : response}];
}
if (valid) {
NSArray<SDWebImageDownloaderOperationToken *> *tokens;
@synchronized (self) {
tokens = [self.callbackTokens copy];
}
for (SDWebImageDownloaderOperationToken *token in tokens) {
if (token.progressBlock) {
token.progressBlock(0, expected, self.request.URL);
}
}
} else {
// Status code invalid and marked as cancelled. Do not call `[self.dataTask cancel]` which may mass up URLSession life cycle
disposition = NSURLSessionResponseCancel;
}
__block typeof(self) strongSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:strongSelf];
});
if (completionHandler) {
completionHandler(disposition);
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
if (!self.imageData) {
self.imageData = [[NSMutableData alloc] initWithCapacity:self.expectedSize];
}
[self.imageData appendData:data];
self.receivedSize = self.imageData.length;
NSArray<SDWebImageDownloaderOperationToken *> *tokens;
@synchronized (self) {
tokens = [self.callbackTokens copy];
}
if (self.expectedSize == 0) {
// Unknown expectedSize, immediately call progressBlock and return
for (SDWebImageDownloaderOperationToken *token in tokens) {
if (token.progressBlock) {
token.progressBlock(self.receivedSize, self.expectedSize, self.request.URL);
}
}
return;
}
// Get the finish status
BOOL finished = (self.receivedSize >= self.expectedSize);
// Get the current progress
double currentProgress = (double)self.receivedSize / (double)self.expectedSize;
double previousProgress = self.previousProgress;
double progressInterval = currentProgress - previousProgress;
// Check if we need callback progress
if (!finished && (progressInterval < self.minimumProgressInterval)) {
return;
}
self.previousProgress = currentProgress;
// Using data decryptor will disable the progressive decoding, since there are no support for progressive decrypt
BOOL supportProgressive = (self.options & SDWebImageDownloaderProgressiveLoad) && !self.decryptor;
// When multiple thumbnail decoding use different size, this progressive decoding will cause issue because each callback assume called with different size's image, can not share the same decoding part
// We currently only pick the first thumbnail size, see #3423 talks
// Progressive decoding Only decode partial image, full image in `URLSession:task:didCompleteWithError:`
if (supportProgressive && !finished) {
// Get the image data
NSData *imageData = self.imageData;
// keep maximum one progressive decode process during download
if (imageData && self.coderQueue.operationCount == 0) {
// NSOperation have autoreleasepool, don't need to create extra one
@weakify(self);
[self.coderQueue addOperationWithBlock:^{
@strongify(self);
if (!self) {
return;
}
// When cancelled or transfer finished (`didCompleteWithError`), cancel the progress callback, only completed block is called and enough
@synchronized (self) {
if (self.isCancelled || self.isDownloadCompleted) {
return;
}
}
UIImage *image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, NO, self, [[self class] imageOptionsFromDownloaderOptions:self.options], self.context);
if (image) {
// We do not keep the progressive decoding image even when `finished`=YES. Because they are for view rendering but not take full function from downloader options. And some coders implementation may not keep consistent between progressive decoding and normal decoding.
[self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO];
}
}];
}
}
for (SDWebImageDownloaderOperationToken *token in tokens) {
if (token.progressBlock) {
token.progressBlock(self.receivedSize, self.expectedSize, self.request.URL);
}
}
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
NSCachedURLResponse *cachedResponse = proposedResponse;
if (!(self.options & SDWebImageDownloaderUseNSURLCache)) {
// Prevents caching of responses
cachedResponse = nil;
}
if (completionHandler) {
completionHandler(cachedResponse);
}
}
#pragma mark NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
// If we already cancel the operation or anything mark the operation finished, don't callback twice
if (self.isFinished) return;
self.downloadCompleted = YES;
NSArray<SDWebImageDownloaderOperationToken *> *tokens;
@synchronized (self) {
tokens = [self.callbackTokens copy];
self.dataTask = nil;
__block typeof(self) strongSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf];
if (!error) {
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:strongSelf];
}
});
}
// make sure to call `[self done]` to mark operation as finished
if (error) {
// custom error instead of URLSession error
if (self.responseError) {
error = self.responseError;
}
[self callCompletionBlocksWithError:error];
[self done];
} else {
if (tokens.count > 0) {
NSData *imageData = self.imageData;
// data decryptor
if (imageData && self.decryptor) {
imageData = [self.decryptor decryptedDataWithData:imageData response:self.response];
}
if (imageData) {
/** if you specified to only use cached data via `SDWebImageDownloaderIgnoreCachedResponse`,
* then we should check if the cached data is equal to image data
*/
if (self.options & SDWebImageDownloaderIgnoreCachedResponse && [self.cachedData isEqualToData:imageData]) {
self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain
code:SDWebImageErrorCacheNotModified
userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image is not modified and ignored",
SDWebImageErrorDownloadResponseKey : self.response}];
// call completion block with not modified error
[self callCompletionBlocksWithError:self.responseError];
[self done];
} else {
// decode the image in coder queue, cancel all previous decoding process
[self.coderQueue cancelAllOperations];
[self startCoderOperationWithImageData:imageData
pendingTokens:tokens
finishedTokens:@[]];
}
} else {
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]];
[self done];
}
} else {
[self done];
}
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
} else {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
disposition = NSURLSessionAuthChallengeUseCredential;
}
} else {
if (challenge.previousFailureCount == 0) {
if (self.credential) {
credential = self.credential;
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
// Web Server like Nginx can set `ssl_verify_client` to optional but not always on
// We'd better use default handling here
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
}
if (completionHandler) {
completionHandler(disposition, credential);
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)) {
self.metrics = metrics;
}
#pragma mark Helper methods
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ (SDWebImageOptions)imageOptionsFromDownloaderOptions:(SDWebImageDownloaderOptions)downloadOptions {
SDWebImageOptions options = 0;
if (downloadOptions & SDWebImageDownloaderScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages;
if (downloadOptions & SDWebImageDownloaderDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly;
if (downloadOptions & SDWebImageDownloaderPreloadAllFrames) options |= SDWebImagePreloadAllFrames;
if (downloadOptions & SDWebImageDownloaderAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage;
if (downloadOptions & SDWebImageDownloaderMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass;
return options;
}
#pragma clang diagnostic pop
- (BOOL)shouldContinueWhenAppEntersBackground {
return SD_OPTIONS_CONTAINS(self.options, SDWebImageDownloaderContinueInBackground);
}
- (void)callCompletionBlocksWithError:(nullable NSError *)error {
[self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES];
}
- (void)callCompletionBlocksWithImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
error:(nullable NSError *)error
finished:(BOOL)finished {
NSArray<SDWebImageDownloaderOperationToken *> *tokens;
@synchronized (self) {
tokens = [self.callbackTokens copy];
}
for (SDWebImageDownloaderOperationToken *token in tokens) {
SDWebImageDownloaderCompletedBlock completedBlock = token.completedBlock;
if (completedBlock) {
SDCallbackQueue *queue = self.context[SDWebImageContextCallbackQueue];
[(queue ?: SDCallbackQueue.mainQueue) async:^{
completedBlock(image, imageData, error, finished);
}];
}
}
}
- (void)callCompletionBlockWithToken:(nonnull SDWebImageDownloaderOperationToken *)token
image:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
error:(nullable NSError *)error
finished:(BOOL)finished {
SDWebImageDownloaderCompletedBlock completedBlock = token.completedBlock;
if (completedBlock) {
SDCallbackQueue *queue = self.context[SDWebImageContextCallbackQueue];
[(queue ?: SDCallbackQueue.mainQueue) async:^{
completedBlock(image, imageData, error, finished);
}];
}
}
@end

View File

@@ -0,0 +1,72 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
typedef NSURLRequest * _Nullable (^SDWebImageDownloaderRequestModifierBlock)(NSURLRequest * _Nonnull request);
/**
This is the protocol for downloader request modifier.
We can use a block to specify the downloader request modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options.
*/
@protocol SDWebImageDownloaderRequestModifier <NSObject>
/// Modify the original URL request and return a new one instead. You can modify the HTTP header, cachePolicy, etc for this URL.
/// @param request The original URL request for image loading
/// @note If return nil, the URL request will be cancelled.
- (nullable NSURLRequest *)modifiedRequestWithRequest:(nonnull NSURLRequest *)request;
@end
/**
A downloader request modifier class with block.
*/
@interface SDWebImageDownloaderRequestModifier : NSObject <SDWebImageDownloaderRequestModifier>
/// Create the request modifier with block
/// @param block A block to control modifier logic
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block;
/// Create the request modifier with block
/// @param block A block to control modifier logic
+ (nonnull instancetype)requestModifierWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end
/**
A convenient request modifier to provide the HTTP request including HTTP Method, Headers and Body.
*/
@interface SDWebImageDownloaderRequestModifier (Conveniences)
/// Create the request modifier with HTTP Method.
/// @param method HTTP Method, nil means to GET.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithMethod:(nullable NSString *)method;
/// Create the request modifier with HTTP Headers.
/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original request.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithHeaders:(nullable NSDictionary<NSString *, NSString *> *)headers;
/// Create the request modifier with HTTP Body.
/// @param body HTTP Body.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithBody:(nullable NSData *)body;
/// Create the request modifier with HTTP Method, Headers and Body.
/// @param method HTTP Method, nil means to GET.
/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original request.
/// @param body HTTP Body.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithMethod:(nullable NSString *)method headers:(nullable NSDictionary<NSString *, NSString *> *)headers body:(nullable NSData *)body;
@end

View File

@@ -0,0 +1,71 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderRequestModifier.h"
@interface SDWebImageDownloaderRequestModifier ()
@property (nonatomic, copy, nonnull) SDWebImageDownloaderRequestModifierBlock block;
@end
@implementation SDWebImageDownloaderRequestModifier
- (instancetype)initWithBlock:(SDWebImageDownloaderRequestModifierBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)requestModifierWithBlock:(SDWebImageDownloaderRequestModifierBlock)block {
SDWebImageDownloaderRequestModifier *requestModifier = [[SDWebImageDownloaderRequestModifier alloc] initWithBlock:block];
return requestModifier;
}
- (NSURLRequest *)modifiedRequestWithRequest:(NSURLRequest *)request {
if (!self.block) {
return nil;
}
return self.block(request);
}
@end
@implementation SDWebImageDownloaderRequestModifier (Conveniences)
- (instancetype)initWithMethod:(NSString *)method {
return [self initWithMethod:method headers:nil body:nil];
}
- (instancetype)initWithHeaders:(NSDictionary<NSString *,NSString *> *)headers {
return [self initWithMethod:nil headers:headers body:nil];
}
- (instancetype)initWithBody:(NSData *)body {
return [self initWithMethod:nil headers:nil body:body];
}
- (instancetype)initWithMethod:(NSString *)method headers:(NSDictionary<NSString *,NSString *> *)headers body:(NSData *)body {
method = method ? [method copy] : @"GET";
headers = [headers copy];
body = [body copy];
return [self initWithBlock:^NSURLRequest * _Nullable(NSURLRequest * _Nonnull request) {
NSMutableURLRequest *mutableRequest = [request mutableCopy];
mutableRequest.HTTPMethod = method;
mutableRequest.HTTPBody = body;
for (NSString *header in headers) {
NSString *value = headers[header];
[mutableRequest setValue:value forHTTPHeaderField:header];
}
return [mutableRequest copy];
}];
}
@end

View File

@@ -0,0 +1,72 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
typedef NSURLResponse * _Nullable (^SDWebImageDownloaderResponseModifierBlock)(NSURLResponse * _Nonnull response);
/**
This is the protocol for downloader response modifier.
We can use a block to specify the downloader response modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options.
*/
@protocol SDWebImageDownloaderResponseModifier <NSObject>
/// Modify the original URL response and return a new response. You can use this to check MIME-Type, mock server response, etc.
/// @param response The original URL response, note for HTTP request it's actually a `NSHTTPURLResponse` instance
/// @note If nil is returned, the image download will marked as cancelled with error `SDWebImageErrorInvalidDownloadResponse`
- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response;
@end
/**
A downloader response modifier class with block.
*/
@interface SDWebImageDownloaderResponseModifier : NSObject <SDWebImageDownloaderResponseModifier>
/// Create the response modifier with block
/// @param block A block to control modifier logic
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block;
/// Create the response modifier with block
/// @param block A block to control modifier logic
+ (nonnull instancetype)responseModifierWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end
/**
A convenient response modifier to provide the HTTP response including HTTP Status Code, Version and Headers.
*/
@interface SDWebImageDownloaderResponseModifier (Conveniences)
/// Create the response modifier with HTTP Status code.
/// @param statusCode HTTP Status Code.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithStatusCode:(NSInteger)statusCode;
/// Create the response modifier with HTTP Version. Status code defaults to 200.
/// @param version HTTP Version, nil means "HTTP/1.1".
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithVersion:(nullable NSString *)version;
/// Create the response modifier with HTTP Headers. Status code defaults to 200.
/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original response.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithHeaders:(nullable NSDictionary<NSString *, NSString *> *)headers;
/// Create the response modifier with HTTP Status Code, Version and Headers.
/// @param statusCode HTTP Status Code.
/// @param version HTTP Version, nil means "HTTP/1.1".
/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original response.
/// @note This is for convenience, if you need code to control the logic, use block API instead.
- (nonnull instancetype)initWithStatusCode:(NSInteger)statusCode version:(nullable NSString *)version headers:(nullable NSDictionary<NSString *, NSString *> *)headers;
@end

View File

@@ -0,0 +1,73 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderResponseModifier.h"
@interface SDWebImageDownloaderResponseModifier ()
@property (nonatomic, copy, nonnull) SDWebImageDownloaderResponseModifierBlock block;
@end
@implementation SDWebImageDownloaderResponseModifier
- (instancetype)initWithBlock:(SDWebImageDownloaderResponseModifierBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)responseModifierWithBlock:(SDWebImageDownloaderResponseModifierBlock)block {
SDWebImageDownloaderResponseModifier *responseModifier = [[SDWebImageDownloaderResponseModifier alloc] initWithBlock:block];
return responseModifier;
}
- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response {
if (!self.block) {
return nil;
}
return self.block(response);
}
@end
@implementation SDWebImageDownloaderResponseModifier (Conveniences)
- (instancetype)initWithStatusCode:(NSInteger)statusCode {
return [self initWithStatusCode:statusCode version:nil headers:nil];
}
- (instancetype)initWithVersion:(NSString *)version {
return [self initWithStatusCode:200 version:version headers:nil];
}
- (instancetype)initWithHeaders:(NSDictionary<NSString *,NSString *> *)headers {
return [self initWithStatusCode:200 version:nil headers:headers];
}
- (instancetype)initWithStatusCode:(NSInteger)statusCode version:(NSString *)version headers:(NSDictionary<NSString *,NSString *> *)headers {
version = version ? [version copy] : @"HTTP/1.1";
headers = [headers copy];
return [self initWithBlock:^NSURLResponse * _Nullable(NSURLResponse * _Nonnull response) {
if (![response isKindOfClass:NSHTTPURLResponse.class]) {
return response;
}
NSMutableDictionary *mutableHeaders = [((NSHTTPURLResponse *)response).allHeaderFields mutableCopy];
for (NSString *header in headers) {
NSString *value = headers[header];
mutableHeaders[header] = value;
}
NSHTTPURLResponse *httpResponse = [[NSHTTPURLResponse alloc] initWithURL:response.URL statusCode:statusCode HTTPVersion:version headerFields:[mutableHeaders copy]];
return httpResponse;
}];
}
@end

View File

@@ -0,0 +1,33 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Jamie Pinkham
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
/// An error domain represent SDWebImage loading system with custom codes
FOUNDATION_EXPORT NSErrorDomain const _Nonnull SDWebImageErrorDomain;
/// The response instance for invalid download response (NSURLResponse *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadResponseKey;
/// The HTTP status code for invalid download response (NSNumber *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey;
/// The HTTP MIME content type for invalid download response (NSString *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadContentTypeKey;
/// SDWebImage error domain and codes
typedef NS_ERROR_ENUM(SDWebImageErrorDomain, SDWebImageError) {
SDWebImageErrorInvalidURL = 1000, // The URL is invalid, such as nil URL or corrupted URL
SDWebImageErrorBadImageData = 1001, // The image data can not be decoded to image, or the image data is empty
SDWebImageErrorCacheNotModified = 1002, // The remote location specify that the cached image is not modified, such as the HTTP response 304 code. It's useful for `SDWebImageRefreshCached`
SDWebImageErrorBlackListed = 1003, // The URL is blacklisted because of unrecoverable failure marked by downloader (such as 404), you can use `.retryFailed` option to avoid this
SDWebImageErrorInvalidDownloadOperation = 2000, // The image download operation is invalid, such as nil operation or unexpected error occur when operation initialized
SDWebImageErrorInvalidDownloadStatusCode = 2001, // The image download response a invalid status code. You can check the status code in error's userInfo under `SDWebImageErrorDownloadStatusCodeKey`
SDWebImageErrorCancelled = 2002, // The image loading operation is cancelled before finished, during either async disk cache query, or waiting before actual network request. For actual network request error, check `NSURLErrorDomain` error domain and code.
SDWebImageErrorInvalidDownloadResponse = 2003, // When using response modifier, the modified download response is nil and marked as failed.
SDWebImageErrorInvalidDownloadContentType = 2004, // The image download response a invalid content type. You can check the MIME content type in error's userInfo under `SDWebImageErrorDownloadContentTypeKey`
};

View File

@@ -0,0 +1,16 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Jamie Pinkham
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageError.h"
NSErrorDomain const _Nonnull SDWebImageErrorDomain = @"SDWebImageErrorDomain";
NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadResponseKey = @"SDWebImageErrorDownloadResponseKey";
NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey = @"SDWebImageErrorDownloadStatusCodeKey";
NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadContentTypeKey = @"SDWebImageErrorDownloadContentTypeKey";

View File

@@ -0,0 +1,119 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_UIKIT || SD_MAC
/**
A protocol to custom the indicator during the image loading.
All of these methods are called from main queue.
*/
@protocol SDWebImageIndicator <NSObject>
@required
/**
The view associate to the indicator.
@return The indicator view
*/
@property (nonatomic, strong, readonly, nonnull) UIView *indicatorView;
/**
Start the animating for indicator.
*/
- (void)startAnimatingIndicator;
/**
Stop the animating for indicator.
*/
- (void)stopAnimatingIndicator;
@optional
/**
Update the loading progress (0-1.0) for indicator. Optional
@param progress The progress, value between 0 and 1.0
*/
- (void)updateIndicatorProgress:(double)progress;
@end
#pragma mark - Activity Indicator
/**
Activity indicator class.
for UIKit(macOS), it use a `UIActivityIndicatorView`.
for AppKit(macOS), it use a `NSProgressIndicator` with the spinning style.
*/
@interface SDWebImageActivityIndicator : NSObject <SDWebImageIndicator>
#if SD_UIKIT
@property (nonatomic, strong, readonly, nonnull) UIActivityIndicatorView *indicatorView;
#else
@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView;
#endif
@end
/**
Convenience way to use activity indicator.
*/
@interface SDWebImageActivityIndicator (Conveniences)
#if !SD_VISION
/// These indicator use the fixed color without dark mode support
/// gray-style activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayIndicator;
/// large gray-style activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayLargeIndicator;
/// white-style activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteIndicator;
/// large white-style activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteLargeIndicator;
#endif
/// These indicator use the system style, supports dark mode if available (iOS 13+/macOS 10.14+)
/// large activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *largeIndicator;
/// medium activity indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *mediumIndicator;
@end
#pragma mark - Progress Indicator
/**
Progress indicator class.
for UIKit(macOS), it use a `UIProgressView`.
for AppKit(macOS), it use a `NSProgressIndicator` with the bar style.
*/
@interface SDWebImageProgressIndicator : NSObject <SDWebImageIndicator>
#if SD_UIKIT
@property (nonatomic, strong, readonly, nonnull) UIProgressView *indicatorView;
#else
@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView;
#endif
@end
/**
Convenience way to create progress indicator. Remember to specify the indicator width or use layout constraint if need.
*/
@interface SDWebImageProgressIndicator (Conveniences)
/// default-style progress indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *defaultIndicator;
#if SD_UIKIT
/// bar-style progress indicator
@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *barIndicator API_UNAVAILABLE(tvos);
#endif
@end
#endif

View File

@@ -0,0 +1,291 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageIndicator.h"
#if SD_UIKIT || SD_MAC
#if SD_MAC
#import <QuartzCore/QuartzCore.h>
#import <CoreImage/CIFilter.h>
#endif
#pragma mark - Activity Indicator
@interface SDWebImageActivityIndicator ()
#if SD_UIKIT
@property (nonatomic, strong, readwrite, nonnull) UIActivityIndicatorView *indicatorView;
#else
@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView;
#endif
@end
@implementation SDWebImageActivityIndicator
- (instancetype)init {
self = [super init];
if (self) {
[self commonInit];
}
return self;
}
#if SD_UIKIT
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)commonInit {
#if SD_VISION
UIActivityIndicatorViewStyle style = UIActivityIndicatorViewStyleMedium;
#else
UIActivityIndicatorViewStyle style;
if (@available(iOS 13.0, tvOS 13.0, *)) {
style = UIActivityIndicatorViewStyleMedium;
} else {
style = UIActivityIndicatorViewStyleWhite;
}
#endif
self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
}
#pragma clang diagnostic pop
#endif
#if SD_MAC
- (void)commonInit {
self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect];
self.indicatorView.style = NSProgressIndicatorStyleSpinning;
self.indicatorView.controlSize = NSControlSizeSmall;
[self.indicatorView sizeToFit];
self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin;
}
#endif
- (void)startAnimatingIndicator {
#if SD_UIKIT
[self.indicatorView startAnimating];
#else
[self.indicatorView startAnimation:nil];
#endif
self.indicatorView.hidden = NO;
}
- (void)stopAnimatingIndicator {
#if SD_UIKIT
[self.indicatorView stopAnimating];
#else
[self.indicatorView stopAnimation:nil];
#endif
self.indicatorView.hidden = YES;
}
@end
@implementation SDWebImageActivityIndicator (Conveniences)
#if !SD_VISION
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ (SDWebImageActivityIndicator *)grayIndicator {
SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new];
#if SD_UIKIT
#if SD_IOS
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
#else
indicator.indicatorView.color = [UIColor colorWithWhite:0 alpha:0.45]; // Color from `UIActivityIndicatorViewStyleGray`
#endif
#else
indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support
#endif
return indicator;
}
+ (SDWebImageActivityIndicator *)grayLargeIndicator {
SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.grayIndicator;
#if SD_UIKIT
UIColor *grayColor = indicator.indicatorView.color;
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
indicator.indicatorView.color = grayColor;
#else
indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support
indicator.indicatorView.controlSize = NSControlSizeRegular;
#endif
[indicator.indicatorView sizeToFit];
return indicator;
}
+ (SDWebImageActivityIndicator *)whiteIndicator {
SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new];
#if SD_UIKIT
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
#else
indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support
CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
[lighten setDefaults];
[lighten setValue:@(1) forKey:kCIInputBrightnessKey];
indicator.indicatorView.contentFilters = @[lighten];
#endif
return indicator;
}
+ (SDWebImageActivityIndicator *)whiteLargeIndicator {
SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.whiteIndicator;
#if SD_UIKIT
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
#else
indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support
indicator.indicatorView.controlSize = NSControlSizeRegular;
[indicator.indicatorView sizeToFit];
#endif
return indicator;
}
#endif
+ (SDWebImageActivityIndicator *)largeIndicator {
SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new];
#if SD_VISION
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge;
#elif SD_UIKIT
if (@available(iOS 13.0, tvOS 13.0, *)) {
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge;
} else {
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
}
#else
indicator.indicatorView.controlSize = NSControlSizeRegular;
[indicator.indicatorView sizeToFit];
#endif
return indicator;
}
+ (SDWebImageActivityIndicator *)mediumIndicator {
SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new];
#if SD_VISION
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium;
#elif SD_UIKIT
if (@available(iOS 13.0, tvOS 13.0, *)) {
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium;
} else {
indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
}
#else
indicator.indicatorView.controlSize = NSControlSizeSmall;
[indicator.indicatorView sizeToFit];
#endif
return indicator;
}
#pragma clang diagnostic pop
@end
#pragma mark - Progress Indicator
@interface SDWebImageProgressIndicator ()
#if SD_UIKIT
@property (nonatomic, strong, readwrite, nonnull) UIProgressView *indicatorView;
#else
@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView;
#endif
@end
@implementation SDWebImageProgressIndicator
- (instancetype)init {
self = [super init];
if (self) {
[self commonInit];
}
return self;
}
#if SD_UIKIT
- (void)commonInit {
self.indicatorView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
}
#endif
#if SD_MAC
- (void)commonInit {
self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 160, 0)]; // Width from `UIProgressView` default width
self.indicatorView.style = NSProgressIndicatorStyleBar;
self.indicatorView.controlSize = NSControlSizeSmall;
[self.indicatorView sizeToFit];
self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin;
}
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
- (void)startAnimatingIndicator {
self.indicatorView.hidden = NO;
#if SD_UIKIT
if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) {
// Ignore NSProgress
} else {
self.indicatorView.progress = 0;
}
#else
self.indicatorView.indeterminate = YES;
self.indicatorView.doubleValue = 0;
[self.indicatorView startAnimation:nil];
#endif
}
- (void)stopAnimatingIndicator {
self.indicatorView.hidden = YES;
#if SD_UIKIT
if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) {
// Ignore NSProgress
} else {
self.indicatorView.progress = 1;
}
#else
self.indicatorView.indeterminate = NO;
self.indicatorView.doubleValue = 100;
[self.indicatorView stopAnimation:nil];
#endif
}
- (void)updateIndicatorProgress:(double)progress {
#if SD_UIKIT
if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) {
// Ignore NSProgress
} else {
[self.indicatorView setProgress:progress animated:YES];
}
#else
self.indicatorView.indeterminate = progress > 0 ? NO : YES;
self.indicatorView.doubleValue = progress * 100;
#endif
}
#pragma clang diagnostic pop
@end
@implementation SDWebImageProgressIndicator (Conveniences)
+ (SDWebImageProgressIndicator *)defaultIndicator {
SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new];
return indicator;
}
#if SD_UIKIT
+ (SDWebImageProgressIndicator *)barIndicator API_UNAVAILABLE(tvos) {
SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new];
indicator.indicatorView.progressViewStyle = UIProgressViewStyleBar;
return indicator;
}
#endif
@end
#endif

View File

@@ -0,0 +1,290 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* 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 "SDImageCacheDefine.h"
#import "SDImageLoader.h"
#import "SDImageTransformer.h"
#import "SDWebImageCacheKeyFilter.h"
#import "SDWebImageCacheSerializer.h"
#import "SDWebImageOptionsProcessor.h"
typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
/**
A combined operation representing the cache and loader operation. You can use it to cancel the load process.
*/
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
/**
Cancel the current operation, including cache and loader process
*/
- (void)cancel;
/// Whether the operation has been cancelled.
@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled;
/**
The cache operation from the image cache query
*/
@property (strong, nonatomic, nullable, readonly) id<SDWebImageOperation> cacheOperation;
/**
The loader operation from the image loader (such as download operation)
*/
@property (strong, nonatomic, nullable, readonly) id<SDWebImageOperation> loaderOperation;
@end
@class SDWebImageManager;
/**
The manager delegate protocol.
*/
@protocol SDWebImageManagerDelegate <NSObject>
@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:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nonnull NSURL *)imageURL;
/**
* Controls the complicated logic to mark as failed URLs when download error occur.
* If the delegate implement this method, we will not use the built-in way to mark URL as failed based on error code;
@param imageManager The current `SDWebImageManager`
@param imageURL The url of the image
@param error The download error for the url
@return Whether to block this url or not. Return YES to mark this URL as failed.
*/
- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error;
@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 loadImageWithURL:imageURL
options:0
progress:nil
completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
// do something with image
}
}];
* @endcode
*/
@interface SDWebImageManager : NSObject
/**
* The delegate for manager. Defaults to nil.
*/
@property (weak, nonatomic, nullable) id <SDWebImageManagerDelegate> delegate;
/**
* The image cache used by manager to query image cache.
*/
@property (strong, nonatomic, readonly, nonnull) id<SDImageCache> imageCache;
/**
* The image loader used by manager to load image.
*/
@property (strong, nonatomic, readonly, nonnull) id<SDImageLoader> imageLoader;
/**
The image transformer for manager. It's used for image transform after the image load finished and store the transformed image to cache, see `SDImageTransformer`.
Defaults to nil, which means no transform is applied.
@note This will affect all the load requests for this manager if you provide. However, you can pass `SDWebImageContextImageTransformer` in context arg to explicitly use that transformer instead.
*/
@property (strong, nonatomic, nullable) id<SDImageTransformer> transformer;
/**
* The cache filter is used to convert an URL into a cache key each time SDWebImageManager need cache key to use image cache.
*
* 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.cacheKeyFilter =[SDWebImageCacheKeyFilter cacheKeyFilterWithBlock:^NSString * _Nullable(NSURL * _Nonnull url) {
url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
return [url absoluteString];
}];
* @endcode
*/
@property (nonatomic, strong, nullable) id<SDWebImageCacheKeyFilter> cacheKeyFilter;
/**
* The cache serializer is used to convert the decoded image, the source downloaded data, to the actual data used for storing to the disk cache. If you return nil, means to generate the data from the image instance, see `SDImageCache`.
* For example, if you are using WebP images and facing the slow decoding time issue when later retrieving from disk cache again. You can try to encode the decoded image to JPEG/PNG format to disk cache instead of source downloaded data.
* @note The `image` arg is nonnull, but when you also provide an image transformer and the image is transformed, the `data` arg may be nil, take attention to this case.
* @note This method is called from a global queue in order to not to block the main thread.
* @code
SDWebImageManager.sharedManager.cacheSerializer = [SDWebImageCacheSerializer cacheSerializerWithBlock:^NSData * _Nullable(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL) {
SDImageFormat format = [NSData sd_imageFormatForImageData:data];
switch (format) {
case SDImageFormatWebP:
return image.images ? data : nil;
default:
return data;
}
}];
* @endcode
* The default value is nil. Means we just store the source downloaded data to disk cache.
*/
@property (nonatomic, strong, nullable) id<SDWebImageCacheSerializer> cacheSerializer;
/**
The options processor is used, to have a global control for all the image request options and context option for current manager.
@note If you use `transformer`, `cacheKeyFilter` or `cacheSerializer` property of manager, the input context option already apply those properties before passed. This options processor is a better replacement for those property in common usage.
For example, you can control the global options, based on the URL or original context option like the below code.
* @code
SDWebImageManager.sharedManager.optionsProcessor = [SDWebImageOptionsProcessor optionsProcessorWithBlock:^SDWebImageOptionsResult * _Nullable(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
// Only do animation on `SDAnimatedImageView`
if (!context[SDWebImageContextAnimatedImageClass]) {
options |= SDWebImageDecodeFirstFrameOnly;
}
// Do not force decode for png url
if ([url.lastPathComponent isEqualToString:@"png"]) {
options |= SDWebImageAvoidDecodeImage;
}
// Always use screen scale factor
SDWebImageMutableContext *mutableContext = [NSDictionary dictionaryWithDictionary:context];
mutableContext[SDWebImageContextImageScaleFactor] = @(UIScreen.mainScreen.scale);
context = [mutableContext copy];
return [[SDWebImageOptionsResult alloc] initWithOptions:options context:context];
}];
* @endcode
*/
@property (nonatomic, strong, nullable) id<SDWebImageOptionsProcessor> optionsProcessor;
/**
* Check one or more operations running
*/
@property (nonatomic, assign, readonly, getter=isRunning) BOOL running;
/**
The default image cache when the manager which is created with no arguments. Such as shared manager or init.
Defaults to nil. Means using `SDImageCache.sharedImageCache`
*/
@property (nonatomic, class, nullable) id<SDImageCache> defaultImageCache;
/**
The default image loader for manager which is created with no arguments. Such as shared manager or init.
Defaults to nil. Means using `SDWebImageDownloader.sharedDownloader`
*/
@property (nonatomic, class, nullable) id<SDImageLoader> defaultImageLoader;
/**
* Returns global shared manager instance.
*/
@property (nonatomic, class, readonly, nonnull) SDWebImageManager *sharedManager;
/**
* Allows to specify instance of cache and image loader used with image manager.
* @return new instance of `SDWebImageManager` with specified cache and loader.
*/
- (nonnull instancetype)initWithCache:(nonnull id<SDImageCache>)cache loader:(nonnull id<SDImageLoader>)loader NS_DESIGNATED_INITIALIZER;
/**
* 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
* @note the progress block is executed on a background queue
* @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 and the NSData representation as second parameter.
* In case of error the image parameter is nil and the third parameter may contain an NSError.
*
* The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache
* or from the memory cache or from the network.
*
* The fifth parameter is set to NO when the SDWebImageProgressiveLoad option is used and the image is
* downloading. This block is thus called repeatedly 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.
*
* The last parameter is the original image URL
*
* @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process.
*/
- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nonnull SDInternalCompletionBlock)completedBlock;
/**
* 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed.
*
* @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process.
*/
- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nonnull SDInternalCompletionBlock)completedBlock;
/**
* Cancel all current operations
*/
- (void)cancelAll;
/**
* Remove the specify URL from failed black list.
* @param url The failed URL.
*/
- (void)removeFailedURL:(nonnull NSURL *)url;
/**
* Remove all the URL from failed black list.
*/
- (void)removeAllFailedURLs;
/**
* Return the cache key for a given URL, does not considerate transformer or thumbnail.
* @note This method does not have context option, only use the url and manager level cacheKeyFilter to generate the cache key.
*/
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url;
/**
* Return the cache key for a given URL and context option.
* @note The context option like `.thumbnailPixelSize` and `.imageTransformer` will effect the generated cache key, using this if you have those context associated.
*/
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context;
@end

View File

@@ -0,0 +1,800 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageManager.h"
#import "SDImageCache.h"
#import "SDWebImageDownloader.h"
#import "UIImage+Metadata.h"
#import "SDAssociatedObject.h"
#import "SDWebImageError.h"
#import "SDInternalMacros.h"
#import "SDCallbackQueue.h"
static id<SDImageCache> _defaultImageCache;
static id<SDImageLoader> _defaultImageLoader;
@interface SDWebImageCombinedOperation ()
@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
@property (strong, nonatomic, readwrite, nullable) id<SDWebImageOperation> loaderOperation;
@property (strong, nonatomic, readwrite, nullable) id<SDWebImageOperation> cacheOperation;
@property (weak, nonatomic, nullable) SDWebImageManager *manager;
@end
@interface SDWebImageManager () {
SD_LOCK_DECLARE(_failedURLsLock); // a lock to keep the access to `failedURLs` thread-safe
SD_LOCK_DECLARE(_runningOperationsLock); // a lock to keep the access to `runningOperations` thread-safe
}
@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
@property (strong, nonatomic, readwrite, nonnull) id<SDImageLoader> imageLoader;
@property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;
@property (strong, nonatomic, nonnull) NSMutableSet<SDWebImageCombinedOperation *> *runningOperations;
@end
@implementation SDWebImageManager
+ (id<SDImageCache>)defaultImageCache {
return _defaultImageCache;
}
+ (void)setDefaultImageCache:(id<SDImageCache>)defaultImageCache {
if (defaultImageCache && ![defaultImageCache conformsToProtocol:@protocol(SDImageCache)]) {
return;
}
_defaultImageCache = defaultImageCache;
}
+ (id<SDImageLoader>)defaultImageLoader {
return _defaultImageLoader;
}
+ (void)setDefaultImageLoader:(id<SDImageLoader>)defaultImageLoader {
if (defaultImageLoader && ![defaultImageLoader conformsToProtocol:@protocol(SDImageLoader)]) {
return;
}
_defaultImageLoader = defaultImageLoader;
}
+ (nonnull instancetype)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (nonnull instancetype)init {
id<SDImageCache> cache = [[self class] defaultImageCache];
if (!cache) {
cache = [SDImageCache sharedImageCache];
}
id<SDImageLoader> loader = [[self class] defaultImageLoader];
if (!loader) {
loader = [SDWebImageDownloader sharedDownloader];
}
return [self initWithCache:cache loader:loader];
}
- (nonnull instancetype)initWithCache:(nonnull id<SDImageCache>)cache loader:(nonnull id<SDImageLoader>)loader {
if ((self = [super init])) {
_imageCache = cache;
_imageLoader = loader;
_failedURLs = [NSMutableSet new];
SD_LOCK_INIT(_failedURLsLock);
_runningOperations = [NSMutableSet new];
SD_LOCK_INIT(_runningOperationsLock);
}
return self;
}
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
if (!url) {
return @"";
}
NSString *key;
// Cache Key Filter
id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
if (cacheKeyFilter) {
key = [cacheKeyFilter cacheKeyForURL:url];
} else {
key = url.absoluteString;
}
return key;
}
- (nullable NSString *)originalCacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context {
if (!url) {
return @"";
}
NSString *key;
// Cache Key Filter
id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
if (context[SDWebImageContextCacheKeyFilter]) {
cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
}
if (cacheKeyFilter) {
key = [cacheKeyFilter cacheKeyForURL:url];
} else {
key = url.absoluteString;
}
return key;
}
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context {
if (!url) {
return @"";
}
NSString *key;
// Cache Key Filter
id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
if (context[SDWebImageContextCacheKeyFilter]) {
cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
}
if (cacheKeyFilter) {
key = [cacheKeyFilter cacheKeyForURL:url];
} else {
key = url.absoluteString;
}
// Thumbnail Key Appending
NSValue *thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize];
if (thumbnailSizeValue != nil) {
CGSize thumbnailSize = CGSizeZero;
#if SD_MAC
thumbnailSize = thumbnailSizeValue.sizeValue;
#else
thumbnailSize = thumbnailSizeValue.CGSizeValue;
#endif
BOOL preserveAspectRatio = YES;
NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio];
if (preserveAspectRatioValue != nil) {
preserveAspectRatio = preserveAspectRatioValue.boolValue;
}
key = SDThumbnailedKeyForKey(key, thumbnailSize, preserveAspectRatio);
}
// Transformer Key Appending
id<SDImageTransformer> transformer = self.transformer;
if (context[SDWebImageContextImageTransformer]) {
transformer = context[SDWebImageContextImageTransformer];
if ([transformer isEqual:NSNull.null]) {
transformer = nil;
}
}
if (transformer) {
key = SDTransformedKeyForKey(key, transformer.transformerKey);
}
return key;
}
- (SDWebImageCombinedOperation *)loadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDInternalCompletionBlock)completedBlock {
return [self loadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock];
}
- (SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nonnull SDInternalCompletionBlock)completedBlock {
// Invoking this method without a completedBlock is pointless
NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
// 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;
}
SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
operation.manager = self;
BOOL isFailedUrl = NO;
if (url) {
SD_LOCK(_failedURLsLock);
isFailedUrl = [self.failedURLs containsObject:url];
SD_UNLOCK(_failedURLsLock);
}
// Preprocess the options and context arg to decide the final the result for manager
SDWebImageOptionsResult *result = [self processedResultForURL:url options:options context:context];
if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
NSString *description = isFailedUrl ? @"Image url is blacklisted" : @"Image url is nil";
NSInteger code = isFailedUrl ? SDWebImageErrorBlackListed : SDWebImageErrorInvalidURL;
[self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : description}] queue:result.context[SDWebImageContextCallbackQueue] url:url];
return operation;
}
SD_LOCK(_runningOperationsLock);
[self.runningOperations addObject:operation];
SD_UNLOCK(_runningOperationsLock);
// Start the entry to load image from cache, the longest steps are below
// Steps without transformer:
// 1. query image from cache, miss
// 2. download data and image
// 3. store image to cache
// Steps with transformer:
// 1. query transformed image from cache, miss
// 2. query original image from cache, miss
// 3. download data and image
// 4. do transform in CPU
// 5. store original image to cache
// 6. store transformed image to cache
[self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock];
return operation;
}
- (void)cancelAll {
SD_LOCK(_runningOperationsLock);
NSSet<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
SD_UNLOCK(_runningOperationsLock);
[copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array
}
- (BOOL)isRunning {
BOOL isRunning = NO;
SD_LOCK(_runningOperationsLock);
isRunning = (self.runningOperations.count > 0);
SD_UNLOCK(_runningOperationsLock);
return isRunning;
}
- (void)removeFailedURL:(NSURL *)url {
if (!url) {
return;
}
SD_LOCK(_failedURLsLock);
[self.failedURLs removeObject:url];
SD_UNLOCK(_failedURLsLock);
}
- (void)removeAllFailedURLs {
SD_LOCK(_failedURLsLock);
[self.failedURLs removeAllObjects];
SD_UNLOCK(_failedURLsLock);
}
#pragma mark - Private
// Query normal cache process
- (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDInternalCompletionBlock)completedBlock {
// Grab the image cache to use
id<SDImageCache> imageCache = context[SDWebImageContextImageCache];
if (!imageCache) {
imageCache = self.imageCache;
}
// Get the query cache type
SDImageCacheType queryCacheType = SDImageCacheTypeAll;
if (context[SDWebImageContextQueryCacheType]) {
queryCacheType = [context[SDWebImageContextQueryCacheType] integerValue];
}
// Check whether we should query cache
BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly);
if (shouldQueryCache) {
// transformed cache key
NSString *key = [self cacheKeyForURL:url context:context];
// to avoid the SDImageCache's sync logic use the mismatched cache key
// we should strip the `thumbnail` related context
SDWebImageMutableContext *mutableContext = [context mutableCopy];
mutableContext[SDWebImageContextImageThumbnailPixelSize] = nil;
mutableContext[SDWebImageContextImagePreserveAspectRatio] = nil;
@weakify(operation);
operation.cacheOperation = [imageCache queryImageForKey:key options:options context:mutableContext cacheType:queryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
@strongify(operation);
if (!operation || operation.isCancelled) {
// Image combined operation cancelled by user
[self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url];
[self safelyRemoveOperationFromRunning:operation];
return;
} else if (!cachedImage) {
NSString *originKey = [self originalCacheKeyForURL:url context:context];
BOOL mayInOriginalCache = ![key isEqualToString:originKey];
// Have a chance to query original cache instead of downloading, then applying transform
// Thumbnail decoding is done inside SDImageCache's decoding part, which does not need post processing for transform
if (mayInOriginalCache) {
[self callOriginalCacheProcessForOperation:operation url:url options:options context:context progress:progressBlock completed:completedBlock];
return;
}
}
// Continue download process
[self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock];
}];
} else {
// Continue download process
[self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
}
}
// Query original cache process
- (void)callOriginalCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDInternalCompletionBlock)completedBlock {
// Grab the image cache to use, choose standalone original cache firstly
id<SDImageCache> imageCache = context[SDWebImageContextOriginalImageCache];
if (!imageCache) {
// if no standalone cache available, use default cache
imageCache = context[SDWebImageContextImageCache];
if (!imageCache) {
imageCache = self.imageCache;
}
}
// Get the original query cache type
SDImageCacheType originalQueryCacheType = SDImageCacheTypeDisk;
if (context[SDWebImageContextOriginalQueryCacheType]) {
originalQueryCacheType = [context[SDWebImageContextOriginalQueryCacheType] integerValue];
}
// Check whether we should query original cache
BOOL shouldQueryOriginalCache = (originalQueryCacheType != SDImageCacheTypeNone);
if (shouldQueryOriginalCache) {
// Get original cache key generation without transformer
NSString *key = [self originalCacheKeyForURL:url context:context];
@weakify(operation);
operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:originalQueryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
@strongify(operation);
if (!operation || operation.isCancelled) {
// Image combined operation cancelled by user
[self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url];
[self safelyRemoveOperationFromRunning:operation];
return;
} else if (!cachedImage) {
// Original image cache miss. Continue download process
[self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
return;
}
// Skip downloading and continue transform process, and ignore .refreshCached option for now
[self callTransformProcessForOperation:operation url:url options:options context:context originalImage:cachedImage originalData:cachedData cacheType:cacheType finished:YES completed:completedBlock];
[self safelyRemoveOperationFromRunning:operation];
}];
} else {
// Continue download process
[self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
}
}
// Download process
- (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(SDWebImageContext *)context
cachedImage:(nullable UIImage *)cachedImage
cachedData:(nullable NSData *)cachedData
cacheType:(SDImageCacheType)cacheType
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDInternalCompletionBlock)completedBlock {
// Mark the cache operation end
@synchronized (operation) {
operation.cacheOperation = nil;
}
// Grab the image loader to use
id<SDImageLoader> imageLoader = context[SDWebImageContextImageLoader];
if (!imageLoader) {
imageLoader = self.imageLoader;
}
// Check whether we should download image from network
BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly);
shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached);
shouldDownload &= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]);
if ([imageLoader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) {
shouldDownload &= [imageLoader canRequestImageForURL:url options:options context:context];
} else {
shouldDownload &= [imageLoader canRequestImageForURL:url];
}
if (shouldDownload) {
if (cachedImage && options & SDWebImageRefreshCached) {
// If image was found in the cache but 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.
[self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
// Pass the cached image to the image loader. The image loader should check whether the remote image is equal to the cached image.
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
mutableContext[SDWebImageContextLoaderCachedImage] = cachedImage;
context = [mutableContext copy];
}
@weakify(operation);
operation.loaderOperation = [imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
@strongify(operation);
if (!operation || operation.isCancelled) {
// Image combined operation cancelled by user
[self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] queue:context[SDWebImageContextCallbackQueue] url:url];
} else if (cachedImage && options & SDWebImageRefreshCached && [error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCacheNotModified) {
// Image refresh hit the NSURLCache cache, do not call the completion block
} else if ([error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCancelled) {
// Download operation cancelled by user before sending the request, don't block failed URL
[self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url];
} else if (error) {
[self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url];
BOOL shouldBlockFailedURL = [self shouldBlockFailedURLWithURL:url error:error options:options context:context];
if (shouldBlockFailedURL) {
SD_LOCK(self->_failedURLsLock);
[self.failedURLs addObject:url];
SD_UNLOCK(self->_failedURLsLock);
}
} else {
if ((options & SDWebImageRetryFailed)) {
SD_LOCK(self->_failedURLsLock);
[self.failedURLs removeObject:url];
SD_UNLOCK(self->_failedURLsLock);
}
// Continue transform process
[self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:SDImageCacheTypeNone finished:finished completed:completedBlock];
}
if (finished) {
[self safelyRemoveOperationFromRunning:operation];
}
}];
} else if (cachedImage) {
[self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
[self safelyRemoveOperationFromRunning:operation];
} else {
// Image not in cache and download disallowed by delegate
[self callCompletionBlockForOperation:operation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
[self safelyRemoveOperationFromRunning:operation];
}
}
// Transform process
- (void)callTransformProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(SDWebImageContext *)context
originalImage:(nullable UIImage *)originalImage
originalData:(nullable NSData *)originalData
cacheType:(SDImageCacheType)cacheType
finished:(BOOL)finished
completed:(nullable SDInternalCompletionBlock)completedBlock {
id<SDImageTransformer> transformer = context[SDWebImageContextImageTransformer];
if ([transformer isEqual:NSNull.null]) {
transformer = nil;
}
// transformer check
BOOL shouldTransformImage = originalImage && transformer;
shouldTransformImage = shouldTransformImage && (!originalImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage));
shouldTransformImage = shouldTransformImage && (!originalImage.sd_isVector || (options & SDWebImageTransformVectorImage));
// thumbnail check
BOOL isThumbnail = originalImage.sd_isThumbnail;
NSData *cacheData = originalData;
UIImage *cacheImage = originalImage;
if (isThumbnail) {
cacheData = nil; // thumbnail don't store full size data
originalImage = nil; // thumbnail don't have full size image
}
if (shouldTransformImage) {
// transformed cache key
NSString *key = [self cacheKeyForURL:url context:context];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// Case that transformer on thumbnail, which this time need full pixel image
UIImage *transformedImage = [transformer transformedImageWithImage:cacheImage forKey:key];
if (transformedImage) {
// We need keep some metadata from the full size image when needed
// Because most of our transformer does not care about these information
// So we add a **post-process** logic here, not a good design :(
BOOL preserveImageMetadata = YES;
if ([transformer respondsToSelector:@selector(preserveImageMetadata)]) {
preserveImageMetadata = transformer.preserveImageMetadata;
}
if (preserveImageMetadata) {
SDImageCopyAssociatedObject(cacheImage, transformedImage);
}
// Mark the transformed
transformedImage.sd_isTransformed = YES;
[self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:transformedImage originalData:originalData cacheData:nil cacheType:cacheType finished:finished completed:completedBlock];
} else {
[self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock];
}
});
} else {
[self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock];
}
}
// Store origin cache process
- (void)callStoreOriginCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(SDWebImageContext *)context
originalImage:(nullable UIImage *)originalImage
cacheImage:(nullable UIImage *)cacheImage
originalData:(nullable NSData *)originalData
cacheData:(nullable NSData *)cacheData
cacheType:(SDImageCacheType)cacheType
finished:(BOOL)finished
completed:(nullable SDInternalCompletionBlock)completedBlock {
// Grab the image cache to use, choose standalone original cache firstly
id<SDImageCache> imageCache = context[SDWebImageContextOriginalImageCache];
if (!imageCache) {
// if no standalone cache available, use default cache
imageCache = context[SDWebImageContextImageCache];
if (!imageCache) {
imageCache = self.imageCache;
}
}
// the original store image cache type
SDImageCacheType originalStoreCacheType = SDImageCacheTypeDisk;
if (context[SDWebImageContextOriginalStoreCacheType]) {
originalStoreCacheType = [context[SDWebImageContextOriginalStoreCacheType] integerValue];
}
id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
// If the original cacheType is disk, since we don't need to store the original data again
// Strip the disk from the originalStoreCacheType
if (cacheType == SDImageCacheTypeDisk) {
if (originalStoreCacheType == SDImageCacheTypeDisk) originalStoreCacheType = SDImageCacheTypeNone;
if (originalStoreCacheType == SDImageCacheTypeAll) originalStoreCacheType = SDImageCacheTypeMemory;
}
// Get original cache key generation without transformer
NSString *key = [self originalCacheKeyForURL:url context:context];
if (finished && cacheSerializer && (originalStoreCacheType == SDImageCacheTypeDisk || originalStoreCacheType == SDImageCacheTypeAll)) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData *newOriginalData = [cacheSerializer cacheDataWithImage:originalImage originalData:originalData imageURL:url];
// Store original image and data
[self storeImage:originalImage imageData:newOriginalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{
// Continue store cache process, transformed data is nil
[self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock];
}];
});
} else {
// Store original image and data
[self storeImage:originalImage imageData:originalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{
// Continue store cache process, transformed data is nil
[self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock];
}];
}
}
// Store normal cache process
- (void)callStoreCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
url:(nonnull NSURL *)url
options:(SDWebImageOptions)options
context:(SDWebImageContext *)context
image:(nullable UIImage *)image
data:(nullable NSData *)data
cacheType:(SDImageCacheType)cacheType
finished:(BOOL)finished
completed:(nullable SDInternalCompletionBlock)completedBlock {
// Grab the image cache to use
id<SDImageCache> imageCache = context[SDWebImageContextImageCache];
if (!imageCache) {
imageCache = self.imageCache;
}
// the target image store cache type
SDImageCacheType storeCacheType = SDImageCacheTypeAll;
if (context[SDWebImageContextStoreCacheType]) {
storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue];
}
id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
// transformed cache key
NSString *key = [self cacheKeyForURL:url context:context];
if (finished && cacheSerializer && (storeCacheType == SDImageCacheTypeDisk || storeCacheType == SDImageCacheTypeAll)) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData *newData = [cacheSerializer cacheDataWithImage:image originalData:data imageURL:url];
// Store image and data
[self storeImage:image imageData:newData forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{
[self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url];
}];
});
} else {
// Store image and data
[self storeImage:image imageData:data forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{
[self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url];
}];
}
}
#pragma mark - Helper
- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
if (!operation) {
return;
}
SD_LOCK(_runningOperationsLock);
[self.runningOperations removeObject:operation];
SD_UNLOCK(_runningOperationsLock);
}
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)data
forKey:(nullable NSString *)key
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
imageCache:(nonnull id<SDImageCache>)imageCache
cacheType:(SDImageCacheType)cacheType
finished:(BOOL)finished
completion:(nullable SDWebImageNoParamsBlock)completion {
BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);
// Ignore progressive data cache
if (!finished) {
if (completion) {
completion();
}
return;
}
// Check whether we should wait the store cache finished. If not, callback immediately
if ([imageCache respondsToSelector:@selector(storeImage:imageData:forKey:options:context:cacheType:completion:)]) {
[imageCache storeImage:image imageData:data forKey:key options:options context:context cacheType:cacheType completion:^{
if (waitStoreCache) {
if (completion) {
completion();
}
}
}];
} else {
[imageCache storeImage:image imageData:data forKey:key cacheType:cacheType completion:^{
if (waitStoreCache) {
if (completion) {
completion();
}
}
}];
}
if (!waitStoreCache) {
if (completion) {
completion();
}
}
}
- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
completion:(nullable SDInternalCompletionBlock)completionBlock
error:(nullable NSError *)error
queue:(nullable SDCallbackQueue *)queue
url:(nullable NSURL *)url {
[self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES queue:queue url:url];
}
- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
completion:(nullable SDInternalCompletionBlock)completionBlock
image:(nullable UIImage *)image
data:(nullable NSData *)data
error:(nullable NSError *)error
cacheType:(SDImageCacheType)cacheType
finished:(BOOL)finished
queue:(nullable SDCallbackQueue *)queue
url:(nullable NSURL *)url {
if (completionBlock) {
[(queue ?: SDCallbackQueue.mainQueue) async:^{
completionBlock(image, data, error, cacheType, finished, url);
}];
}
}
- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url
error:(nonnull NSError *)error
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context {
id<SDImageLoader> imageLoader = context[SDWebImageContextImageLoader];
if (!imageLoader) {
imageLoader = self.imageLoader;
}
// Check whether we should block failed url
BOOL shouldBlockFailedURL;
if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) {
shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error];
} else {
if ([imageLoader respondsToSelector:@selector(shouldBlockFailedURLWithURL:error:options:context:)]) {
shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error options:options context:context];
} else {
shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error];
}
}
return shouldBlockFailedURL;
}
- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
SDWebImageOptionsResult *result;
SDWebImageMutableContext *mutableContext = [SDWebImageMutableContext dictionary];
// Image Transformer from manager
if (!context[SDWebImageContextImageTransformer]) {
id<SDImageTransformer> transformer = self.transformer;
[mutableContext setValue:transformer forKey:SDWebImageContextImageTransformer];
}
// Cache key filter from manager
if (!context[SDWebImageContextCacheKeyFilter]) {
id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
[mutableContext setValue:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter];
}
// Cache serializer from manager
if (!context[SDWebImageContextCacheSerializer]) {
id<SDWebImageCacheSerializer> cacheSerializer = self.cacheSerializer;
[mutableContext setValue:cacheSerializer forKey:SDWebImageContextCacheSerializer];
}
if (mutableContext.count > 0) {
if (context) {
[mutableContext addEntriesFromDictionary:context];
}
context = [mutableContext copy];
}
// Apply options processor
if (self.optionsProcessor) {
result = [self.optionsProcessor processedResultForURL:url options:options context:context];
}
if (!result) {
// Use default options result
result = [[SDWebImageOptionsResult alloc] initWithOptions:options context:context];
}
return result;
}
@end
@implementation SDWebImageCombinedOperation
- (BOOL)isCancelled {
// Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK
@synchronized (self) {
return _cancelled;
}
}
- (void)cancel {
// Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK
@synchronized(self) {
if (_cancelled) {
return;
}
_cancelled = YES;
if (self.cacheOperation) {
[self.cacheOperation cancel];
self.cacheOperation = nil;
}
if (self.loaderOperation) {
[self.loaderOperation cancel];
self.loaderOperation = nil;
}
[self.manager safelyRemoveOperationFromRunning:self];
}
}
@end

View File

@@ -0,0 +1,27 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
/// A protocol represents cancelable operation.
@protocol SDWebImageOperation <NSObject>
/// Cancel the operation
- (void)cancel;
@optional
/// Whether the operation has been cancelled.
@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled;
@end
/// NSOperation conform to `SDWebImageOperation`.
@interface NSOperation (SDWebImageOperation) <SDWebImageOperation>
@end

View File

@@ -0,0 +1,14 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageOperation.h"
/// NSOperation conform to `SDWebImageOperation`.
@implementation NSOperation (SDWebImageOperation)
@end

View File

@@ -0,0 +1,78 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDWebImageDefine.h"
@class SDWebImageOptionsResult;
typedef SDWebImageOptionsResult * _Nullable(^SDWebImageOptionsProcessorBlock)(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context);
/**
The options result contains both options and context.
*/
@interface SDWebImageOptionsResult : NSObject
/**
WebCache options.
*/
@property (nonatomic, assign, readonly) SDWebImageOptions options;
/**
Context options.
*/
@property (nonatomic, copy, readonly, nullable) SDWebImageContext *context;
/**
Create a new options result.
@param options options
@param context context
@return The options result contains both options and context.
*/
- (nonnull instancetype)initWithOptions:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end
/**
This is the protocol for options processor.
Options processor can be used, to control the final result for individual image request's `SDWebImageOptions` and `SDWebImageContext`
Implements the protocol to have a global control for each indivadual image request's option.
*/
@protocol SDWebImageOptionsProcessor <NSObject>
/**
Return the processed options result for specify image URL, with its options and context
@param url The URL to the image
@param options A mask to specify options to use for this request
@param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@return The processed result, contains both options and context
*/
- (nullable SDWebImageOptionsResult *)processedResultForURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
@end
/**
A options processor class with block.
*/
@interface SDWebImageOptionsProcessor : NSObject<SDWebImageOptionsProcessor>
- (nonnull instancetype)initWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block;
+ (nonnull instancetype)optionsProcessorWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)new NS_UNAVAILABLE;
@end

View File

@@ -0,0 +1,59 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageOptionsProcessor.h"
@interface SDWebImageOptionsResult ()
@property (nonatomic, assign) SDWebImageOptions options;
@property (nonatomic, copy, nullable) SDWebImageContext *context;
@end
@implementation SDWebImageOptionsResult
- (instancetype)initWithOptions:(SDWebImageOptions)options context:(SDWebImageContext *)context {
self = [super init];
if (self) {
self.options = options;
self.context = context;
}
return self;
}
@end
@interface SDWebImageOptionsProcessor ()
@property (nonatomic, copy, nonnull) SDWebImageOptionsProcessorBlock block;
@end
@implementation SDWebImageOptionsProcessor
- (instancetype)initWithBlock:(SDWebImageOptionsProcessorBlock)block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
+ (instancetype)optionsProcessorWithBlock:(SDWebImageOptionsProcessorBlock)block {
SDWebImageOptionsProcessor *optionsProcessor = [[SDWebImageOptionsProcessor alloc] initWithBlock:block];
return optionsProcessor;
}
- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
if (!self.block) {
return nil;
}
return self.block(url, options, context);
}
@end

View File

@@ -0,0 +1,168 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageManager.h"
@class SDWebImagePrefetcher;
/**
A token represents a list of URLs, can be used to cancel the download.
*/
@interface SDWebImagePrefetchToken : NSObject <SDWebImageOperation>
/**
* Cancel the current prefetching.
*/
- (void)cancel;
/**
list of URLs of current prefetching.
*/
@property (nonatomic, copy, readonly, nullable) NSArray<NSURL *> *urls;
@end
/**
The prefetcher delegate protocol
*/
@protocol SDWebImagePrefetcherDelegate <NSObject>
@optional
/**
* Called when an image was prefetched. Which means it's called when one URL from any of prefetching finished.
*
* @param imagePrefetcher The current image prefetcher
* @param imageURL The image url that was prefetched
* @param finishedCount The total number of images that were prefetched (successful or not)
* @param totalCount The total number of images that were to be prefetched
*/
- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount;
/**
* Called when all images are prefetched. Which means it's called when all URLs from all of prefetching finished.
* @param imagePrefetcher The current image prefetcher
* @param totalCount The total number of images that were prefetched (whether successful or not)
* @param skippedCount The total number of images that were skipped
*/
- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount;
@end
typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls);
typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls);
/**
* Prefetch some URLs in the cache for future use. Images are downloaded in low priority.
*/
@interface SDWebImagePrefetcher : NSObject
/**
* The web image manager used by prefetcher to prefetch images.
* @note You can specify a standalone manager and downloader with custom configuration suitable for image prefetching. Such as `currentDownloadCount` or `downloadTimeout`.
*/
@property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager;
/**
* Maximum number of URLs to prefetch at the same time. Defaults to 3.
*/
@property (nonatomic, assign) NSUInteger maxConcurrentPrefetchCount;
/**
* The options for prefetcher. Defaults to SDWebImageLowPriority.
* @deprecated Prefetcher is designed to be used shared and should not effect others. So in 5.15.0 we added API `prefetchURLs:options:context:`. If you want global control, try to use `SDWebImageOptionsProcessor` in manager level.
*/
@property (nonatomic, assign) SDWebImageOptions options API_DEPRECATED("Use individual prefetch options param instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
/**
* The context for prefetcher. Defaults to nil.
* @deprecated Prefetcher is designed to be used shared and should not effect others. So in 5.15.0 we added API `prefetchURLs:options:context:`. If you want global control, try to use `SDWebImageOptionsProcessor` in `SDWebImageManager.optionsProcessor`.
*/
@property (nonatomic, copy, nullable) SDWebImageContext *context API_DEPRECATED("Use individual prefetch context param instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED));
/**
* Queue options for prefetcher when call the progressBlock, completionBlock and delegate methods. Defaults to Main Queue.
* @deprecated 5.15.0 introduce SDCallbackQueue, use that is preferred and has higher priority. The set/get to this property will translate to that instead.
* @note The call is asynchronously to avoid blocking target queue. (see SDCallbackPolicyDispatch)
* @note The delegate queue should be set before any prefetching start and may not be changed during prefetching to avoid thread-safe problem.
*/
@property (strong, nonatomic, nonnull) dispatch_queue_t delegateQueue API_DEPRECATED("Use SDWebImageContextCallbackQueue context param instead, see SDCallbackQueue", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0));
/**
* The delegate for the prefetcher. Defaults to nil.
*/
@property (weak, nonatomic, nullable) id <SDWebImagePrefetcherDelegate> delegate;
/**
* Returns the global shared image prefetcher instance. It use a standalone manager which is different from shared manager.
*/
@property (nonatomic, class, readonly, nonnull) SDWebImagePrefetcher *sharedImagePrefetcher;
/**
* Allows you to instantiate a prefetcher with any arbitrary image manager.
*/
- (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER;
/**
* Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property.
* Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls.
* Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch.
*
* @param urls list of URLs to prefetch
* @return the token to cancel the current prefetching.
*/
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls;
/**
* Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property.
* Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls.
* Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch.
*
* @param urls list of URLs to prefetch
* @param progressBlock block to be called when progress updates;
* first parameter is the number of completed (successful or not) requests,
* second parameter is the total number of images originally requested to be prefetched
* @param completionBlock block to be called when the current prefetching is completed
* first param is the number of completed (successful or not) requests,
* second parameter is the number of skipped requests
* @return the token to cancel the current prefetching.
*/
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls
progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock;
/**
* Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property.
* Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls.
* Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch.
*
* @param urls list of URLs to prefetch
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock block to be called when progress updates;
* first parameter is the number of completed (successful or not) requests,
* second parameter is the total number of images originally requested to be prefetched
* @param completionBlock block to be called when the current prefetching is completed
* first param is the number of completed (successful or not) requests,
* second parameter is the number of skipped requests
* @return the token to cancel the current prefetching.
*/
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock;
/**
* Remove and cancel all the prefeching for the prefetcher.
*/
- (void)cancelPrefetching;
@end

View File

@@ -0,0 +1,341 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImagePrefetcher.h"
#import "SDAsyncBlockOperation.h"
#import "SDCallbackQueue.h"
#import "SDInternalMacros.h"
#import <stdatomic.h>
@interface SDCallbackQueue ()
@property (nonatomic, strong, nonnull) dispatch_queue_t queue;
@end
@interface SDWebImagePrefetchToken () {
@public
// Though current implementation, `SDWebImageManager` completion block is always on main queue. But however, there is no guarantee in docs. And we may introduce config to specify custom queue in the future.
// These value are just used as incrementing counter, keep thread-safe using memory_order_relaxed for performance.
atomic_ulong _skippedCount;
atomic_ulong _finishedCount;
atomic_flag _isAllFinished;
unsigned long _totalCount;
// Used to ensure NSPointerArray thread safe
SD_LOCK_DECLARE(_prefetchOperationsLock);
SD_LOCK_DECLARE(_loadOperationsLock);
}
@property (nonatomic, copy, readwrite) NSArray<NSURL *> *urls;
@property (nonatomic, strong) NSPointerArray *loadOperations;
@property (nonatomic, strong) NSPointerArray *prefetchOperations;
@property (nonatomic, weak) SDWebImagePrefetcher *prefetcher;
@property (nonatomic, assign) SDWebImageOptions options;
@property (nonatomic, copy, nullable) SDWebImageContext *context;
@property (nonatomic, copy, nullable) SDWebImagePrefetcherCompletionBlock completionBlock;
@property (nonatomic, copy, nullable) SDWebImagePrefetcherProgressBlock progressBlock;
@end
@interface SDWebImagePrefetcher ()
@property (strong, nonatomic, nonnull) SDWebImageManager *manager;
@property (strong, atomic, nonnull) NSMutableSet<SDWebImagePrefetchToken *> *runningTokens;
@property (strong, nonatomic, nonnull) NSOperationQueue *prefetchQueue;
@property (strong, nonatomic, nullable) SDCallbackQueue *callbackQueue;
@end
@implementation SDWebImagePrefetcher
+ (nonnull instancetype)sharedImagePrefetcher {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (nonnull instancetype)init {
return [self initWithImageManager:[SDWebImageManager new]];
}
- (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager {
if ((self = [super init])) {
_manager = manager;
_runningTokens = [NSMutableSet set];
_options = SDWebImageLowPriority;
_prefetchQueue = [NSOperationQueue new];
self.maxConcurrentPrefetchCount = 3;
}
return self;
}
- (void)setMaxConcurrentPrefetchCount:(NSUInteger)maxConcurrentPrefetchCount {
self.prefetchQueue.maxConcurrentOperationCount = maxConcurrentPrefetchCount;
}
- (NSUInteger)maxConcurrentPrefetchCount {
return self.prefetchQueue.maxConcurrentOperationCount;
}
- (void)setDelegateQueue:(dispatch_queue_t)delegateQueue {
// Deprecate and translate to SDCallbackQueue
_callbackQueue = [[SDCallbackQueue alloc] initWithDispatchQueue:delegateQueue];
_callbackQueue.policy = SDCallbackPolicyDispatch;
}
- (dispatch_queue_t)delegateQueue {
// Deprecate and translate to SDCallbackQueue
return (_callbackQueue ?: SDCallbackQueue.mainQueue).queue;
}
#pragma mark - Prefetch
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls {
return [self prefetchURLs:urls progress:nil completed:nil];
}
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls
progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock {
return [self prefetchURLs:urls options:self.options context:self.context progress:progressBlock completed:completionBlock];
}
- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock {
if (!urls || urls.count == 0) {
if (completionBlock) {
completionBlock(0, 0);
}
return nil;
}
SDWebImagePrefetchToken *token = [SDWebImagePrefetchToken new];
token.prefetcher = self;
token.urls = urls;
token.options = options;
token.context = context;
token->_skippedCount = 0;
token->_finishedCount = 0;
token->_totalCount = token.urls.count;
atomic_flag_clear(&(token->_isAllFinished));
token.loadOperations = [NSPointerArray weakObjectsPointerArray];
token.prefetchOperations = [NSPointerArray weakObjectsPointerArray];
token.progressBlock = progressBlock;
token.completionBlock = completionBlock;
[self addRunningToken:token];
[self startPrefetchWithToken:token];
return token;
}
- (void)startPrefetchWithToken:(SDWebImagePrefetchToken * _Nonnull)token {
for (NSURL *url in token.urls) {
@weakify(self);
SDAsyncBlockOperation *prefetchOperation = [SDAsyncBlockOperation blockOperationWithBlock:^(SDAsyncBlockOperation * _Nonnull asyncOperation) {
@strongify(self);
if (!self || asyncOperation.isCancelled) {
return;
}
id<SDWebImageOperation> operation = [self.manager loadImageWithURL:url options:token.options context:token.context progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
@strongify(self);
if (!self) {
return;
}
if (!finished) {
return;
}
atomic_fetch_add_explicit(&(token->_finishedCount), 1, memory_order_relaxed);
if (error) {
// Add last failed
atomic_fetch_add_explicit(&(token->_skippedCount), 1, memory_order_relaxed);
}
// Current operation finished
[self callProgressBlockForToken:token imageURL:imageURL];
if (atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed) == token->_totalCount) {
// All finished
if (!atomic_flag_test_and_set_explicit(&(token->_isAllFinished), memory_order_relaxed)) {
[self callCompletionBlockForToken:token];
[self removeRunningToken:token];
}
}
[asyncOperation complete];
}];
NSAssert(operation != nil, @"Operation should not be nil, [SDWebImageManager loadImageWithURL:options:context:progress:completed:] break prefetch logic");
SD_LOCK(token->_loadOperationsLock);
[token.loadOperations addPointer:(__bridge void *)operation];
SD_UNLOCK(token->_loadOperationsLock);
}];
SD_LOCK(token->_prefetchOperationsLock);
[token.prefetchOperations addPointer:(__bridge void *)prefetchOperation];
SD_UNLOCK(token->_prefetchOperationsLock);
[self.prefetchQueue addOperation:prefetchOperation];
}
}
#pragma mark - Cancel
- (void)cancelPrefetching {
@synchronized(self.runningTokens) {
NSSet<SDWebImagePrefetchToken *> *copiedTokens = [self.runningTokens copy];
[copiedTokens makeObjectsPerformSelector:@selector(cancel)];
[self.runningTokens removeAllObjects];
}
}
- (void)callProgressBlockForToken:(SDWebImagePrefetchToken *)token imageURL:(NSURL *)url {
if (!token) {
return;
}
BOOL shouldCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)];
NSUInteger tokenFinishedCount = [self tokenFinishedCount];
NSUInteger tokenTotalCount = [self tokenTotalCount];
NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
NSUInteger totalCount = token->_totalCount;
SDCallbackQueue *queue = token.context[SDWebImageContextCallbackQueue];
if (!queue) {
queue = self.callbackQueue;
}
[(queue ?: SDCallbackQueue.mainQueue) async:^{
if (shouldCallDelegate) {
[self.delegate imagePrefetcher:self didPrefetchURL:url finishedCount:tokenFinishedCount totalCount:tokenTotalCount];
}
if (token.progressBlock) {
token.progressBlock(finishedCount, totalCount);
}
}];
}
- (void)callCompletionBlockForToken:(SDWebImagePrefetchToken *)token {
if (!token) {
return;
}
BOOL shoulCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)] && ([self countOfRunningTokens] == 1); // last one
NSUInteger tokenTotalCount = [self tokenTotalCount];
NSUInteger tokenSkippedCount = [self tokenSkippedCount];
NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
NSUInteger skippedCount = atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed);
SDCallbackQueue *queue = token.context[SDWebImageContextCallbackQueue];
if (!queue) {
queue = self.callbackQueue;
}
[(queue ?: SDCallbackQueue.mainQueue) async:^{
if (shoulCallDelegate) {
[self.delegate imagePrefetcher:self didFinishWithTotalCount:tokenTotalCount skippedCount:tokenSkippedCount];
}
if (token.completionBlock) {
token.completionBlock(finishedCount, skippedCount);
}
}];
}
#pragma mark - Helper
- (NSUInteger)tokenTotalCount {
NSUInteger tokenTotalCount = 0;
@synchronized (self.runningTokens) {
for (SDWebImagePrefetchToken *token in self.runningTokens) {
tokenTotalCount += token->_totalCount;
}
}
return tokenTotalCount;
}
- (NSUInteger)tokenSkippedCount {
NSUInteger tokenSkippedCount = 0;
@synchronized (self.runningTokens) {
for (SDWebImagePrefetchToken *token in self.runningTokens) {
tokenSkippedCount += atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed);
}
}
return tokenSkippedCount;
}
- (NSUInteger)tokenFinishedCount {
NSUInteger tokenFinishedCount = 0;
@synchronized (self.runningTokens) {
for (SDWebImagePrefetchToken *token in self.runningTokens) {
tokenFinishedCount += atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
}
}
return tokenFinishedCount;
}
- (void)addRunningToken:(SDWebImagePrefetchToken *)token {
if (!token) {
return;
}
@synchronized (self.runningTokens) {
[self.runningTokens addObject:token];
}
}
- (void)removeRunningToken:(SDWebImagePrefetchToken *)token {
if (!token) {
return;
}
@synchronized (self.runningTokens) {
[self.runningTokens removeObject:token];
}
}
- (NSUInteger)countOfRunningTokens {
NSUInteger count = 0;
@synchronized (self.runningTokens) {
count = self.runningTokens.count;
}
return count;
}
@end
@implementation SDWebImagePrefetchToken
- (instancetype)init {
self = [super init];
if (self) {
SD_LOCK_INIT(_prefetchOperationsLock);
SD_LOCK_INIT(_loadOperationsLock);
}
return self;
}
- (void)cancel {
SD_LOCK(_prefetchOperationsLock);
[self.prefetchOperations compact];
for (id operation in self.prefetchOperations) {
id<SDWebImageOperation> strongOperation = operation;
if (strongOperation) {
[strongOperation cancel];
}
}
self.prefetchOperations.count = 0;
SD_UNLOCK(_prefetchOperationsLock);
SD_LOCK(_loadOperationsLock);
[self.loadOperations compact];
for (id operation in self.loadOperations) {
id<SDWebImageOperation> strongOperation = operation;
if (strongOperation) {
[strongOperation cancel];
}
}
self.loadOperations.count = 0;
SD_UNLOCK(_loadOperationsLock);
self.completionBlock = nil;
self.progressBlock = nil;
[self.prefetcher removeRunningToken:self];
}
@end

View File

@@ -0,0 +1,131 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_UIKIT || SD_MAC
#import "SDImageCache.h"
#if SD_UIKIT
typedef UIViewAnimationOptions SDWebImageAnimationOptions;
#else
typedef NS_OPTIONS(NSUInteger, SDWebImageAnimationOptions) {
SDWebImageAnimationOptionAllowsImplicitAnimation = 1 << 0, // specify `allowsImplicitAnimation` for the `NSAnimationContext`
SDWebImageAnimationOptionCurveEaseInOut = 0 << 16, // default
SDWebImageAnimationOptionCurveEaseIn = 1 << 16,
SDWebImageAnimationOptionCurveEaseOut = 2 << 16,
SDWebImageAnimationOptionCurveLinear = 3 << 16,
SDWebImageAnimationOptionTransitionNone = 0 << 20, // default
SDWebImageAnimationOptionTransitionFlipFromLeft = 1 << 20,
SDWebImageAnimationOptionTransitionFlipFromRight = 2 << 20,
SDWebImageAnimationOptionTransitionCurlUp = 3 << 20,
SDWebImageAnimationOptionTransitionCurlDown = 4 << 20,
SDWebImageAnimationOptionTransitionCrossDissolve = 5 << 20,
SDWebImageAnimationOptionTransitionFlipFromTop = 6 << 20,
SDWebImageAnimationOptionTransitionFlipFromBottom = 7 << 20,
};
#endif
typedef void (^SDWebImageTransitionPreparesBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
typedef void (^SDWebImageTransitionAnimationsBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image);
typedef void (^SDWebImageTransitionCompletionBlock)(BOOL finished);
/**
This class is used to provide a transition animation after the view category load image finished. Use this on `sd_imageTransition` in UIView+WebCache.h
for UIKit(iOS & tvOS), we use `+[UIView transitionWithView:duration:options:animations:completion]` for transition animation.
for AppKit(macOS), we use `+[NSAnimationContext runAnimationGroup:completionHandler:]` for transition animation. You can call `+[NSAnimationContext currentContext]` to grab the context during animations block.
@note These transition are provided for basic usage. If you need complicated animation, consider to directly use Core Animation or use `SDWebImageAvoidAutoSetImage` and implement your own after image load finished.
*/
@interface SDWebImageTransition : NSObject
/**
By default, we set the image to the view at the beginning of the animations. You can disable this and provide custom set image process
*/
@property (nonatomic, assign) BOOL avoidAutoSetImage;
/**
The duration of the transition animation, measured in seconds. Defaults to 0.5.
*/
@property (nonatomic, assign) NSTimeInterval duration;
/**
The timing function used for all animations within this transition animation (macOS).
*/
@property (nonatomic, strong, nullable) CAMediaTimingFunction *timingFunction API_UNAVAILABLE(ios, tvos, watchos) API_DEPRECATED("Use SDWebImageAnimationOptions instead, or grab NSAnimationContext.currentContext and modify the timingFunction", macos(10.10, 10.10));
/**
A mask of options indicating how you want to perform the animations.
*/
@property (nonatomic, assign) SDWebImageAnimationOptions animationOptions;
/**
A block object to be executed before the animation sequence starts.
*/
@property (nonatomic, copy, nullable) SDWebImageTransitionPreparesBlock prepares;
/**
A block object that contains the changes you want to make to the specified view.
*/
@property (nonatomic, copy, nullable) SDWebImageTransitionAnimationsBlock animations;
/**
A block object to be executed when the animation sequence ends.
*/
@property (nonatomic, copy, nullable) SDWebImageTransitionCompletionBlock completion;
@end
/**
Convenience way to create transition. Remember to specify the duration if needed.
for UIKit, these transition just use the correspond `animationOptions`. By default we enable `UIViewAnimationOptionAllowUserInteraction` to allow user interaction during transition.
for AppKit, these transition use Core Animation in `animations`. So your view must be layer-backed. Set `wantsLayer = YES` before you apply it.
*/
@interface SDWebImageTransition (Conveniences)
/// Fade-in transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *fadeTransition;
/// Flip from left transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromLeftTransition;
/// Flip from right transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromRightTransition;
/// Flip from top transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromTopTransition;
/// Flip from bottom transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromBottomTransition;
/// Curl up transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlUpTransition;
/// Curl down transition.
@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlDownTransition;
/// Fade-in transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)fadeTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(fade(duration:));
/// Flip from left transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)flipFromLeftTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromLeft(duration:));
/// Flip from right transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)flipFromRightTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromRight(duration:));
/// Flip from top transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)flipFromTopTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromTop(duration:));
/// Flip from bottom transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)flipFromBottomTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromBottom(duration:));
/// Curl up transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)curlUpTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(curlUp(duration:));
/// Curl down transition with duration.
/// @param duration transition duration, use ease-in-out
+ (nonnull instancetype)curlDownTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(curlDown(duration:));
@end
#endif

View File

@@ -0,0 +1,194 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageTransition.h"
#if SD_UIKIT || SD_MAC
#if SD_MAC
#import "SDWebImageTransitionInternal.h"
#import "SDInternalMacros.h"
CAMediaTimingFunction * SDTimingFunctionFromAnimationOptions(SDWebImageAnimationOptions options) {
if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveLinear, options)) {
return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
} else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseIn, options)) {
return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
} else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseOut, options)) {
return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
} else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseInOut, options)) {
return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
} else {
return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
}
}
CATransition * SDTransitionFromAnimationOptions(SDWebImageAnimationOptions options) {
if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCrossDissolve)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionFade;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromLeft)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionPush;
trans.subtype = kCATransitionFromLeft;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromRight)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionPush;
trans.subtype = kCATransitionFromRight;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromTop)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionPush;
trans.subtype = kCATransitionFromTop;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromBottom)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionPush;
trans.subtype = kCATransitionFromBottom;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCurlUp)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionReveal;
trans.subtype = kCATransitionFromTop;
return trans;
} else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCurlDown)) {
CATransition *trans = [CATransition animation];
trans.type = kCATransitionReveal;
trans.subtype = kCATransitionFromBottom;
return trans;
} else {
return nil;
}
}
#endif
@implementation SDWebImageTransition
- (instancetype)init {
self = [super init];
if (self) {
self.duration = 0.5;
}
return self;
}
@end
@implementation SDWebImageTransition (Conveniences)
+ (SDWebImageTransition *)fadeTransition {
return [self fadeTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)fadeTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionCrossDissolve;
#endif
return transition;
}
+ (SDWebImageTransition *)flipFromLeftTransition {
return [self flipFromLeftTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)flipFromLeftTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionFlipFromLeft | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromLeft;
#endif
return transition;
}
+ (SDWebImageTransition *)flipFromRightTransition {
return [self flipFromRightTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)flipFromRightTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionFlipFromRight | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromRight;
#endif
return transition;
}
+ (SDWebImageTransition *)flipFromTopTransition {
return [self flipFromTopTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)flipFromTopTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionFlipFromTop | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromTop;
#endif
return transition;
}
+ (SDWebImageTransition *)flipFromBottomTransition {
return [self flipFromBottomTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)flipFromBottomTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionFlipFromBottom | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromBottom;
#endif
return transition;
}
+ (SDWebImageTransition *)curlUpTransition {
return [self curlUpTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)curlUpTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionCurlUp | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionCurlUp;
#endif
return transition;
}
+ (SDWebImageTransition *)curlDownTransition {
return [self curlDownTransitionWithDuration:0.5];
}
+ (SDWebImageTransition *)curlDownTransitionWithDuration:(NSTimeInterval)duration {
SDWebImageTransition *transition = [SDWebImageTransition new];
transition.duration = duration;
#if SD_UIKIT
transition.animationOptions = UIViewAnimationOptionTransitionCurlDown | UIViewAnimationOptionAllowUserInteraction;
#else
transition.animationOptions = SDWebImageAnimationOptionTransitionCurlDown;
#endif
transition.duration = duration;
return transition;
}
@end
#endif

View File

@@ -0,0 +1,402 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#if SD_UIKIT
#import "SDWebImageManager.h"
/**
* Integrates SDWebImage async downloading and caching of remote images with UIButton.
*/
@interface UIButton (WebCache)
#pragma mark - Image
/**
* Get the current image URL.
* This simply translate to `[self sd_imageURLForState:self.state]` from v5.18.0
*/
@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL;
/**
* Get the image URL for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (nullable NSURL *)sd_imageURLForState:(UIControlState)state;
/**
* Get the image operation key for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (nonnull NSString *)sd_imageOperationKeyForState:(UIControlState)state;
/**
* Set the button `image` with an `url`.
*
* The download 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)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url` and a placeholder.
*
* The download 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 sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
/**
* Set the button `image` with an `url`.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder and custom options.
*
* The download 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 progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `image` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
#pragma mark - Background Image
/**
* Get the current background image URL.
*/
@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentBackgroundImageURL;
/**
* Get the background image operation key for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (nonnull NSString *)sd_backgroundImageOperationKeyForState:(UIControlState)state;
/**
* Get the background image URL for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (nullable NSURL *)sd_backgroundImageURLForState:(UIControlState)state;
/**
* Set the button `backgroundImage` with an `url`.
*
* The download 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)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state NS_REFINED_FOR_SWIFT;
/**
* Set the button `backgroundImage` with an `url` and a placeholder.
*
* The download 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 sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT;
/**
* Set the button `backgroundImage` with an `url`, placeholder and custom options.
*
* The download 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)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the button `backgroundImage` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context;
/**
* Set the button `backgroundImage` with an `url`.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `backgroundImage` with an `url`, placeholder.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the button `backgroundImage` with an `url`, placeholder and custom options.
*
* The download 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 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `backgroundImage` with an `url`, placeholder and custom options.
*
* The download 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
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
/**
* Set the button `backgroundImage` with an `url`, placeholder, custom options and context.
*
* The download 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 context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed. 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 a Boolean
* indicating if the image was retrieved from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
#pragma mark - Cancel
/**
* Cancel the current image download
*/
- (void)sd_cancelImageLoadForState:(UIControlState)state;
/**
* Cancel the current backgroundImage download
*/
- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;
@end
#endif

View File

@@ -0,0 +1,198 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "UIButton+WebCache.h"
#if SD_UIKIT
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"
#import "UIView+WebCacheState.h"
#import "UIView+WebCache.h"
#import "SDInternalMacros.h"
@implementation UIButton (WebCache)
#pragma mark - Image
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}
- (void)sd_setImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
mutableContext[SDWebImageContextSetImageOperationKey] = [self sd_imageOperationKeyForState:state];
@weakify(self);
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
context:mutableContext
setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
@strongify(self);
[self setImage:image forState:state];
}
progress:progressBlock
completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageURL);
}
}];
}
#pragma mark - Background Image
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
forState:(UIControlState)state
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock {
SDWebImageMutableContext *mutableContext;
if (context) {
mutableContext = [context mutableCopy];
} else {
mutableContext = [NSMutableDictionary dictionary];
}
mutableContext[SDWebImageContextSetImageOperationKey] = [self sd_backgroundImageOperationKeyForState:state];
@weakify(self);
[self sd_internalSetImageWithURL:url
placeholderImage:placeholder
options:options
context:mutableContext
setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
@strongify(self);
[self setBackgroundImage:image forState:state];
}
progress:progressBlock
completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, imageURL);
}
}];
}
#pragma mark - Cancel
- (void)sd_cancelImageLoadForState:(UIControlState)state {
[self sd_cancelImageLoadOperationWithKey:[self sd_imageOperationKeyForState:state]];
}
- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state {
[self sd_cancelImageLoadOperationWithKey:[self sd_backgroundImageOperationKeyForState:state]];
}
#pragma mark - State
- (NSString *)sd_imageOperationKeyForState:(UIControlState)state {
return [NSString stringWithFormat:@"UIButtonImageOperation%lu", (unsigned long)state];
}
- (NSString *)sd_backgroundImageOperationKeyForState:(UIControlState)state {
return [NSString stringWithFormat:@"UIButtonBackgroundImageOperation%lu", (unsigned long)state];
}
- (NSURL *)sd_currentImageURL {
NSURL *url = [self sd_imageURLForState:self.state];
if (!url) {
[self sd_imageURLForState:UIControlStateNormal];
}
return url;
}
- (NSURL *)sd_imageURLForState:(UIControlState)state {
return [self sd_imageLoadStateForKey:[self sd_imageOperationKeyForState:state]].url;
}
#pragma mark - Background State
- (NSURL *)sd_currentBackgroundImageURL {
NSURL *url = [self sd_backgroundImageURLForState:self.state];
if (!url) {
url = [self sd_backgroundImageURLForState:UIControlStateNormal];
}
return url;
}
- (NSURL *)sd_backgroundImageURLForState:(UIControlState)state {
return [self sd_imageLoadStateForKey:[self sd_backgroundImageOperationKeyForState:state]].url;
}
@end
#endif

View File

@@ -0,0 +1,24 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Fabrice Aneche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
@interface UIImage (ExtendedCacheData)
/**
Read and Write the extended object and bind it to the image. Which can hold some extra metadata like Image's scale factor, URL rich link, date, etc.
The extended object should conforms to NSCoding, which we use `NSKeyedArchiver` and `NSKeyedUnarchiver` to archive it to data, and write to disk cache.
@note The disk cache preserve both of the data and extended data with the same cache key. For manual query, use the `SDDiskCache` protocol method `extendedDataForKey:` instead.
@note You can specify arbitrary object conforms to NSCoding (NSObject protocol here is used to support object using `NS_ROOT_CLASS`, which is not NSObject subclass). If you load image from disk cache, you should check the extended object class to avoid corrupted data.
@warning This object don't need to implements NSSecureCoding (but it's recommended), because we allows arbitrary class.
*/
@property (nonatomic, strong, nullable) id<NSObject, NSCoding> sd_extendedObject;
@end

View File

@@ -0,0 +1,23 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Fabrice Aneche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "UIImage+ExtendedCacheData.h"
#import <objc/runtime.h>
@implementation UIImage (ExtendedCacheData)
- (id<NSObject, NSCoding>)sd_extendedObject {
return objc_getAssociatedObject(self, @selector(sd_extendedObject));
}
- (void)setSd_extendedObject:(id<NSObject, NSCoding>)sd_extendedObject {
objc_setAssociatedObject(self, @selector(sd_extendedObject), sd_extendedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

View File

@@ -0,0 +1,52 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
/**
UIImage category about force decode feature (avoid Image/IO's lazy decoding during rendering behavior).
*/
@interface UIImage (ForceDecode)
/**
A bool value indicating whether the image has already been decoded. This can help to avoid extra force decode.
Force decode is used for 2 cases:
-- 1. for ImageIO created image (via `CGImageCreateWithImageSource` SPI), it's lazy and we trigger the decode before rendering
-- 2. for non-ImageIO created image (via `CGImageCreate` API), we can ensure it's alignment is suitable to render on screen without copy by CoreAnimation
@note For coder plugin developer, always use the SDImageCoderHelper's `colorSpaceGetDeviceRGB`/`preferredPixelFormat` to create CGImage.
@note For more information why force decode, see: https://github.com/path/FastImageCache#byte-alignment
@note From v5.17.0, the default value is always NO. Use `SDImageForceDecodePolicy` to control complicated policy.
*/
@property (nonatomic, assign) BOOL sd_isDecoded;
/**
Decode the provided image. This is useful if you want to force decode the image before rendering to improve performance.
@param image The image to be decoded
@return The decoded image
*/
+ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image;
/**
Decode and scale down the provided image
@param image The image to be decoded
@return The decoded and scaled down image
*/
+ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image;
/**
Decode and scale down the provided image with limit bytes
@param image The image to be decoded
@param bytes The limit bytes size. Provide 0 to use the build-in limit.
@return The decoded and scaled down image
*/
+ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes;
@end

View File

@@ -0,0 +1,43 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "UIImage+ForceDecode.h"
#import "SDImageCoderHelper.h"
#import "objc/runtime.h"
#import "NSImage+Compatibility.h"
@implementation UIImage (ForceDecode)
- (BOOL)sd_isDecoded {
NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isDecoded));
return [value boolValue];
}
- (void)setSd_isDecoded:(BOOL)sd_isDecoded {
objc_setAssociatedObject(self, @selector(sd_isDecoded), @(sd_isDecoded), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image {
if (!image) {
return nil;
}
return [SDImageCoderHelper decodedImageWithImage:image];
}
+ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image {
return [self sd_decodedAndScaledDownImageWithImage:image limitBytes:0];
}
+ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes {
if (!image) {
return nil;
}
return [SDImageCoderHelper decodedAndScaledDownImageWithImage:image limitBytes:bytes];
}
@end

Some files were not shown because too many files have changed in this diff Show More