Commit e834ce33 by zhangyunjie

bug

parent cfb2c404
......@@ -348,16 +348,12 @@
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-OffcnLiveSDKiOS_Example/Pods-OffcnLiveSDKiOS_Example-frameworks.sh",
"${PODS_ROOT}/../../OffcnLiveSDKiOS/Frameworks/ZGIJKMediaFramework.framework",
"${PODS_ROOT}/../../OffcnLiveSDKiOS/Frameworks/OffcnWhiteBoard.framework",
"${PODS_ROOT}/../../OffcnLiveSDKiOS/Frameworks/WebRTC.framework",
"${PODS_ROOT}/../../OffcnLiveSDKiOS/Frameworks/ZYJSDWebImage.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ZGIJKMediaFramework.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OffcnWhiteBoard.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/WebRTC.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ZYJSDWebImage.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
......
......@@ -8,7 +8,7 @@
Pod::Spec.new do |s|
s.name = 'OffcnLiveSDKiOS'
s.version = '2.6.5.4'
s.version = '2.6.3.8.3'
s.summary = 'OffcnLiveSDKiOS.'
s.description = <<-DESC
......@@ -28,7 +28,7 @@ TODO: Add long description of the pod here.
s.public_header_files = 'OffcnLiveSDKiOS/Classes/*.h'
#vendored_frameworks: 第三方framework
s.vendored_frameworks = ['OffcnLiveSDKiOS/Frameworks/ZGIJKMediaFramework.framework','OffcnLiveSDKiOS/Frameworks/OffcnWhiteBoard.framework','OffcnLiveSDKiOS/Frameworks/WebRTC.framework','OffcnLiveSDKiOS/Frameworks/ZYJSDWebImage.framework']
s.vendored_frameworks = ['OffcnLiveSDKiOS/Frameworks/ZGIJKMediaFramework.framework','OffcnLiveSDKiOS/Frameworks/WebRTC.framework']
#frameworks: 该pod依赖的系统framework
s.frameworks = 'CFNetwork', 'CoreFoundation', 'CoreData', 'Foundation', 'AudioToolbox', 'AVFoundation', 'CoreGraphics', 'CoreMedia', 'CoreVideo', 'MediaPlayer', 'MobileCoreServices', 'OpenGLES', 'QuartzCore', 'UIKit', 'VideoToolbox', 'SystemConfiguration', 'CoreTelephony', 'CoreText', 'ImageIO', 'MapKit'
......
......@@ -29,55 +29,8 @@ typedef NS_ENUM(NSInteger, OffcnReachabilityStatus) {
OffcnRealStatusViaWiFi = 2
};
@interface OffcnDownloadWhiteboardResourcesModel : NSObject
@property (nonatomic, copy) NSString *Idx;
@property (nonatomic, copy) NSString *Tm;
@property (nonatomic, copy) NSString *Url;
@property (nonatomic, copy) NSString *Typ;
@property (nonatomic, assign) BOOL isWb;
@end
@interface OffcnDownloadManagerModel : NSObject
//房间授课模式:0:房间模式,1:白板模式
@property (nonatomic, assign) NSInteger teaching_model;
//白板字体下载地址
@property (nonatomic, copy) NSString *board_font;
//白板字体下载后本地地址
@property (nonatomic, copy) NSString *board_font_local;
//白板wb文件下载地址
@property (nonatomic, copy) NSString *white_board_play_url;
//白板wb文件下载后本地地址
@property (nonatomic, copy) NSString *white_board_play_url_local;
//wb单个地址(key:帧index;value:未下载就是下载地址,已下载就是本地保存地址)
@property (nonatomic, strong) NSMutableDictionary *white_board_play_url_dic;
//回放播放时需要的每秒对应的wb的index
@property (nonatomic, strong) NSMutableArray *white_board_play_url_indexArr;
//白板ppt下载地址
@property (nonatomic, copy) NSString *white_board_resource_url;
//白板ppt下载后本地地址
@property (nonatomic, copy) NSString *white_board_resource_url_local;
//ppt单页地址(key:帧index;value:未下载就是下载地址,已下载就是本地保存地址)
@property (nonatomic, strong) NSMutableDictionary *white_board_resource_url_dic;
//回放播放时需要的每秒对应的ppt的index
@property (nonatomic, strong) NSMutableArray *white_board_resource_url_indexArr;
//已下载数量
@property (nonatomic, assign) BOOL isDownloadComplete_wb;
@property (nonatomic, assign) BOOL isDownloadComplete_ppt;
//对应下载的标识
@property (nonatomic, assign) int64_t param2;
@property (nonatomic, assign) BOOL isHasParam2;
@property (nonatomic, assign) int operationIndex;
//沙盒所有视频所在路径
@property (nonatomic, copy) NSString *documentPath;
//沙盒每个下载视频路径
......@@ -238,22 +191,4 @@ typedef void(^downloadM3u8CallBack)(BOOL isSuccess, NSError *error);
//下载m3u8文件
- (void)downloadM3u8WithModel:(OffcnDownloadManagerModel *)model;
/**
回放下载白板wb和ppt文件
@param model model
*/
- (void)downloadWhiteboardResourcesWithModel:(OffcnDownloadManagerModel *)model finished:(void(^)(OffcnDownloadManagerModel *model_call))finished;
//下载白板字体
- (void)downloadWhiteboardFontWithModel:(OffcnDownloadManagerModel *)model finished:(void(^)(OffcnDownloadManagerModel *model))finished;
//下载单个文件
- (void)downloadResource_oneUrlWithModel:(OffcnDownloadManagerModel *)model finished:(void(^)(BOOL success,NSString *path_local,OffcnDownloadManagerModel *callModel))finished;
//下载下个文件
- (void)downloadResource_nextUrlWithDocumentPath:(NSString *)documentPath password:(NSString *)password urlStr:(NSString *)urlStr;
//白板回放退出房间移除下载的文件
-(void)remuvePlaybackWhiteboardAllFileWithPassword:(NSString *)password documentPath:(NSString *)documentPath;
@end
......@@ -9,7 +9,7 @@
#import <UIKit/UIKit.h>
#import "OffcnShareWindow.h"
static const NSString *OffcnLiveSDKVersion = @"2.6.5.4";
static const NSString *OffcnLiveSDKVersion = @"2.6.3.8.3";
//事件通知
#define kOffcnEventNotification @"kOffcnEventNotification"
......@@ -91,7 +91,7 @@ typedef void(^OffcnSDKEventCallBack)(OffcnSDKEvent event);
@property (nonatomic, assign) CGRect shareWindowFrame;
@property (nonatomic, strong) UIWindow *KKeyWindow;//获取自定义window
@property (nonatomic, strong) UIWindow *oldKKeyWindow;//三方的window
@property (nonatomic, weak) UIViewController *shareVC;
@property (nonatomic, strong) UIViewController *shareVC;
//是否支持全屏
......
//
// OffcnWhiteBoard.h
// OffcnWhiteBoard
//
// Created by offcnPlayer on 2021/2/26.
//
#import <Foundation/Foundation.h>
#import <OffcnWhiteBoard/WhiteboardGLView.h>
#import <OffcnWhiteBoard/WhiteboardType.h>
//! Project version number for OffcnWhiteBoard.
FOUNDATION_EXPORT double OffcnWhiteBoardVersionNumber;
//! Project version string for OffcnWhiteBoard.
FOUNDATION_EXPORT const unsigned char OffcnWhiteBoardVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <OffcnWhiteBoard/PublicHeader.h>
/*
offcn Whiteboard
*/
#import <UIKit/UIKit.h>
#import "WhiteboardType.h"
@protocol WhiteboardEventDelegate <NSObject>
-(void)whiteboardEentCallback:(WhiteboardEventType) eventType param1:(int64_t)param1 param2:(int64_t) param2 data:(NSData*)data;
-(void)whiteboardLostIndexCallback:(int)seq handle:(int64_t)handle;
-(void)whiteboardLostPageCallback:(NSString*)pageID version:(int)version handle:(int64_t)handle;
-(void)whiteboardLogOutputCallback:(NSString*)logMsg;
@end
typedef struct WBPoint{
int x;
int y;
}WBPoint;
@interface WhiteboardGLView : UIView
- (id) initWithFrame:(CGRect)frame playMode:(WhiteboardPlayerMode)playMode delegate:(id<WhiteboardEventDelegate>)delegate;
- (void)initWhiteboard:(id<WhiteboardEventDelegate>)delegate;
- (void)destroyWhiteboard;
- (BOOL)enableWhiteboard:(NSString*)imagePath;
- (BOOL)setEntityType:(WhiteboardEntityType)type;
-(WhiteboardPlayerMode)getCurrentPlayMode;
- (BOOL)whiteboardOpen:(NSData*)info;
- (BOOL)whiteboardLoad:(NSData*)pkt;
-(BOOL)closePrePage:(int64_t)handle;
- (BOOL)setMotionType:(WhiteboardMotionType)type;
//- (BOOL)resize:(int)width height:(int)height;
//start
-(BOOL)motionStart:(CGPoint)point;
-(BOOL)motionMove:(CGPoint)point;
-(BOOL)motionStop:(CGPoint)point;
-(BOOL)setEntityColor:(int)color;
-(BOOL)setEntityLineThickness:(float)thickness;
-(BOOL)setEntityFillType:(WhiteboardPaintStyle)type;
-(BOOL)setText:(int64_t)handle text:(NSString*)text;
-(BOOL)setFont:(NSString*)fontLocalPath fontUrl:(NSString*)fontUrl;
-(BOOL)createImage:(NSString*)localPath url:(NSString*)url;
-(BOOL)insertImage:(int64_t)handle path:(NSString*)path;
-(BOOL)createCanvas:(NSString*)imagePath;
-(BOOL)headCanvas;
-(BOOL)tailCanvas;
-(BOOL)nextCanvas;
-(BOOL)prevCanvas;
-(BOOL)deleteCanvas;
-(BOOL)clearCanvas;
-(BOOL)redraw;
-(BOOL)draw;
-(void)resize;
-(BOOL)clearWhiteboardData;
-(BOOL)setTextAction:(int64_t)handle action:(int)action;
-(BOOL)setTextCursor:(int64_t)handle cursorType:(int)cursorType;
-(BOOL)setFontColor:(int64_t)handle fontColor:(int)fontColor;
-(BOOL)setFontSize:(int64_t)handle fontSize:(float)fontSize;
-(BOOL)setFontStyle:(int64_t)handle fontStyle:(int)fontStyle;
-(NSString*)getImageUrl:(int64_t)handle;
-(BOOL)setViewScale:(float)scale isOptimize:(BOOL)isOptimize;
-(float)getViewScale;
-(BOOL)setViewScaleCenterPoint:(WBPoint)point;
-(WBPoint)getViewScrollPoint;
-(BOOL)setViewScrollPoint:(WBPoint)point isOptimize:(BOOL)isOptimize;
-(WBPoint)getViewScrollRange;
-(BOOL)pushWhiteboardDataFromPlayer:(NSData*)data;
-(BOOL)pushWhiteboardDataFromFile:(NSString*)filePath operationSeq:(int)operationSeq;
-(BOOL)pushWhiteboardDataFromFileWithHandle:(NSString*)filePath operationSeq:(int)operationSeq handle:(int64_t)handle;
@property(nonatomic) CGFloat scaleFactor;
@property(weak,nonatomic) id<WhiteboardEventDelegate> eventDelegate;
@end
//
// WhiteboardType.h
// OffcnWhiteboard
//
// Created by offcnPlayer on 2021/3/11.
//
#ifndef WhiteboardType_h
#define WhiteboardType_h
typedef enum WhiteboardEntityType
{
WhiteboardEntityLine = 0,
WhiteboardEntityRect,
WhiteboardEntityOval,
WhiteboardEntityPath,
WhiteboardEntityText,
WhiteboardEntityImage,
WWhiteboardEntityCount
}WhiteboardEntityType;
typedef enum WhiteboardMotionType
{
WhiteboardNewEntity = 0,
WhiteboardDelEntity,
WhiteboardEditEntity,
}WhiteboardMotionType;
typedef enum WhiteboardEventType
{
WhiteboardEventBag,
WhiteboardEventIdr,
WhiteboardEventOpen,
WhiteboardEventClose,
WhiteboardEventClear,
WhiteboardEntityBag,
WhiteboardEntityAdd,
WhiteboardEntityDel,
WhiteboardEntityFront,
WhiteboardEntityBack,
WhiteboardEntityEdt,
WhiteboardEntityMove,
WhiteboardTextEdt,
WhiteboardEntityEnd,
WhiteboardEventCreate,
WhiteboardEventCatch,
WhiteboardEntitySel,
WhiteboardEntityUnSel,
WhiteboardTextInputStart,
WhiteboardTextInputStop,
WhiteboardImageLoad,
WhiteboardFontLoad,
WhiteboardHTMLLoad,
WhiteboardRedraw,
WhiteboardPacketOut,
WhiteboardEventEnd,
WhiteboardUnknownEvent
}WhiteboardEventType;
typedef enum WhiteboardPaintStyle
{
WhiteboardPaintStyleFill=0x00,
WhiteboardPaintStyleStroke,
WhiteboardPaintStyleFillStroke
}WhiteboardPaintStyle;
typedef enum WhiteboardPlayerMode
{
WhiteboardPlayerLiving=0x00,
WhiteboardPlayerVOD
}WhiteboardPlayerMode;
#endif /* WhiteboardType_h */
framework module OffcnWhiteBoard {
umbrella header "OffcnWhiteBoard.h"
export *
module * { export * }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Headers/OffcnWhiteBoard.h</key>
<data>
eoUOERJgC/EboBgwqGwPSE7IySQ=
</data>
<key>Headers/WhiteboardGLView.h</key>
<data>
/wKlDWFjb0ML0VgSG+E72x7fQsw=
</data>
<key>Headers/WhiteboardType.h</key>
<data>
K8qgz8pdWWPbtYuSpBrrkCV4MKQ=
</data>
<key>Info.plist</key>
<data>
jymCLyM/Ef+kSZUrNsK4/93+Tb4=
</data>
<key>Modules/module.modulemap</key>
<data>
il8gSRETznRJV25lh83Q25QHuCg=
</data>
</dict>
<key>files2</key>
<dict>
<key>Headers/OffcnWhiteBoard.h</key>
<dict>
<key>hash</key>
<data>
eoUOERJgC/EboBgwqGwPSE7IySQ=
</data>
<key>hash2</key>
<data>
1c6ZLrhx2tyugDOvzDdR1wL4InqgI69zLR6ffko/nZQ=
</data>
</dict>
<key>Headers/WhiteboardGLView.h</key>
<dict>
<key>hash</key>
<data>
/wKlDWFjb0ML0VgSG+E72x7fQsw=
</data>
<key>hash2</key>
<data>
Tv8KQXrcEzXiVQbsV3nhwTcR1Mq4BV2jF+VOVW6YcR4=
</data>
</dict>
<key>Headers/WhiteboardType.h</key>
<dict>
<key>hash</key>
<data>
K8qgz8pdWWPbtYuSpBrrkCV4MKQ=
</data>
<key>hash2</key>
<data>
OWbOEOMqaT8uoxDbTywCJjv4xe9plm+bcflRUrIIccU=
</data>
</dict>
<key>Modules/module.modulemap</key>
<dict>
<key>hash</key>
<data>
il8gSRETznRJV25lh83Q25QHuCg=
</data>
<key>hash2</key>
<data>
xMQWtGbxqUiZG8TFkJLi+LtOSYRx6yM/mUE3q4gqxyI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
......@@ -126,8 +126,6 @@ typedef enum IJKLogLevel {
@property (nonatomic, retain) id<IJKMediaUrlOpenDelegate> liveOpenDelegate;
@property (nonatomic, retain) id<IJKMediaNativeInvokeDelegate> nativeInvokeDelegate;
@property (nonatomic, retain) id<OFFCNWhiteboardDelegate> whiteboardDataDelegate;
- (void)didShutdown;
......
......@@ -58,11 +58,6 @@ typedef NS_ENUM(NSInteger, IJKMPMoviePullState) {
IJKMPMoviePullStateSuccessed
};
typedef NS_ENUM(NSInteger, IJKMPMoviePlayerAndWhiteboardStyle) {
IJKMPMovieWhiteboardStyle,
IJKMPMoviePlayerStyle
};
typedef NS_ENUM(NSInteger, IJKMPMovieWarningType) {
IJKMPMovieBufferEmptyWarning,
IJKMPMovieAVLostSynWarning,
......@@ -219,15 +214,6 @@ IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidBufferEnoughNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidPullStreamStateNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidPullStreamStateUserInfoKey;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidPlayerAndWhiteboardCommandNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidPlayerAndWhiteboardCommandUserInfoKey;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerWhiteboardIndexNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerWhiteboardIndexUserInfoKey;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerWhiteboardOpenTypeNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerWhiteboardOpenTypeUserInfoKey;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerDidKeyFrameNotification;
IJK_EXTERN NSString *const ZGIJKMPMoviePlayerWarningNotification;
......@@ -288,13 +274,6 @@ typedef NS_ENUM(NSInteger, IJKMediaEvent) {
@end
@protocol OFFCNWhiteboardDelegate <NSObject>
- (void)whiteboardDataCallback:(NSData*)data;
- (void)whiteboardCommandInfo:(int)commandType param:(int)param;
@end
@protocol IJKMediaNativeInvokeDelegate <NSObject>
- (int)invoke:(IJKMediaEvent)event attributes:(NSDictionary *)attributes;
......
......@@ -34,19 +34,6 @@ typedef NS_ENUM(NSInteger,PlayerState)
PLAYER_STATE_SEEK_COMPLETED
};
typedef NS_ENUM(NSInteger,ZGPlayerThirdPartyCommand) {
COMMAND_WHITEBOARD_MAIN_SHOW,
COMMAND_PLAYER_MAIN_SHOW,
};
typedef NS_ENUM(NSInteger,ZGPlayerAndWhiteboardCurOpenType) {
COMMAND_CURRENT_OPEN_NONE,
COMMAND_CURRENT_OPEN_WHITEBOARD,
COMMAND_CURRENT_OPEN_COURSEWARE,
COMMAND_CURRENT_OPEN_COURSEWARE_AND_WHITEBOARD,
};
@protocol PlayerStateDelegate <NSObject>
@optional
......@@ -54,11 +41,6 @@ typedef NS_ENUM(NSInteger,ZGPlayerAndWhiteboardCurOpenType) {
-(void) onPlayerStateChanged:(PlayerState) playerState;
-(void) onCurrentPosition:(NSTimeInterval)curPos totalDuration:(NSTimeInterval)duration;
-(void) onWhiteboardData:(NSData*)data;
-(void) onWhiteboardOperationIndex:(int)operationIndex;
-(void) onCurrentOpenType:(ZGPlayerAndWhiteboardCurOpenType)type;
-(void) onCommand:(ZGPlayerThirdPartyCommand)command param:(int)param;
@end
......@@ -78,9 +60,6 @@ typedef enum ZGPlayerType {
TYPE_MPMOIVE_PLAYER = 3,
} ZGPlayerType;
@property(nonatomic, strong) NSURL* url; // 拉流地址
@property(nonatomic,weak) id<PlayerStateDelegate> delegate;
......
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImage.h"
#if ZYJSD_UIKIT || ZYJSD_MAC
#import <MapKit/MapKit.h>
/**
* Integrates ZYJSDWebImage async downloading and caching of remote images with MKAnnotationView.
*/
@interface MKAnnotationView (ZYJWebCache)
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)ZYJSD_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 ZYJSD_setImageWithURL:placeholderImage:options:
*/
- (void)ZYJSD_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 ZYJSDWebImageOptions for the possible values.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
completed:(nullable ZYJSDExternalCompletionBlock)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#if ZYJSD_MAC
#import "UIImage+ZYJTransform.h"
@interface NSBezierPath (ZYJSDRoundedCorners)
/**
Convenience way to create a bezier path with the specify rounding corners on macOS. Same as the one on `UIBezierPath`.
*/
+ (nonnull instancetype)ZYJSD_bezierPathWithRoundedRect:(NSRect)rect byRoundingCorners:(ZYJSDRectCorner)corners cornerRadius:(CGFloat)cornerRadius;
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.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 `ZYJSDImageCoder` for more detailed information.
*/
typedef NSInteger ZYJSDImageFormat NS_TYPED_EXTENSIBLE_ENUM;
static const ZYJSDImageFormat ZYJSDImageFormatUndefined = -1;
static const ZYJSDImageFormat ZYJSDImageFormatJPEG = 0;
static const ZYJSDImageFormat ZYJSDImageFormatPNG = 1;
static const ZYJSDImageFormat ZYJSDImageFormatGIF = 2;
static const ZYJSDImageFormat ZYJSDImageFormatTIFF = 3;
static const ZYJSDImageFormat ZYJSDImageFormatWebP = 4;
static const ZYJSDImageFormat ZYJSDImageFormatHEIC = 5;
static const ZYJSDImageFormat ZYJSDImageFormatHEIF = 6;
static const ZYJSDImageFormat ZYJSDImageFormatPDF = 7;
static const ZYJSDImageFormat ZYJSDImageFormatSVG = 8;
/**
NSData category about the image content type and UTI.
*/
@interface NSData (ZYJImageContentType)
/**
* Return image format
*
* @param data the input image data
*
* @return the image format as `ZYJSDImageFormat` (enum)
*/
+ (ZYJSDImageFormat)ZYJSD_imageFormatForImageData:(nullable NSData *)data;
/**
* Convert ZYJSDImageFormat to UTType
*
* @param format Format as ZYJSDImageFormat
* @return The UTType as CFStringRef
* @note For unknown format, `kUTTypeImage` abstract type will return
*/
+ (nonnull CFStringRef)ZYJSD_UTTypeFromImageFormat:(ZYJSDImageFormat)format CF_RETURNS_NOT_RETAINED NS_SWIFT_NAME(ZYJSD_UTType(from:));
/**
* Convert UTType to ZYJSDImageFormat
*
* @param uttype The UTType as CFStringRef
* @return The Format as ZYJSDImageFormat
* @note For unknown type, `ZYJSDImageFormatUndefined` will return
*/
+ (ZYJSDImageFormat)ZYJSD_imageFormatFromUTType:(nonnull CFStringRef)uttype;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#if ZYJSD_MAC
/**
This category is provided to easily write cross-platform(AppKit/UIKit) code. For common usage, see `UIImage+ZYJMetadata.h`.
*/
@interface NSImage (ZYJCompatibility)
/**
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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
@interface UIColor (ZYJSDHexString)
/**
Convenience way to get hex string from color. The output should always be 32-bit RGBA hex string like `#00000000`.
*/
@property (nonatomic, copy, readonly, nonnull) NSString *ZYJSD_hexString;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
@interface UIImage (ZYJExtendedCacheData)
/**
Read and Write the extended object and bind it to the image. Which can hold some extra ZYJMetadata 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 `ZYJSDDiskCache` 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> ZYJSD_extendedObject;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/**
UIImage category about force decode feature (avoid Image/IO's lazy decoding during rendering behavior).
*/
@interface UIImage (ZYJForceDecode)
/**
A bool value indicating whether the image has already been decoded. This can help to avoid extra force decode.
*/
@property (nonatomic, assign) BOOL ZYJSD_iZYJSDecoded;
/**
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 *)ZYJSD_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 *)ZYJSD_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 *)ZYJSD_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes;
@end
/*
* This file is part of the ZYJSDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
* (c) Laurin Brandner
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "ZYJSDWebImageCompat.h"
/**
This category is just use as a convenience method. For more detail control, use methods in `UIImage+ZYJMultiFormat.h` or directly use `ZYJSDImageCoder`.
*/
@interface UIImage (ZYJGIF)
/**
Creates an animated UIImage from an NSData.
This will create animated image if the data is Animated GIF. And will create a static image is the data is Static GIF.
@param data The GIF data
@return The created image
*/
+ (nullable UIImage *)ZYJSD_imageWithGIFData:(nullable NSData *)data;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/**
UIImage category for memory cache cost.
*/
@interface UIImage (ZYJMemoryCacheCost)
/**
The memory cache cost for specify image used by image cache. The cost function is the bytes size held in memory.
If you set some associated object to `UIImage`, you can set the custom value to indicate the memory cost.
For `UIImage`, this method return the single frame bytes size when `image.images` is nil for static image. Return full frame bytes size when `image.images` is not nil for animated image.
For `NSImage`, this method return the single frame bytes size because `NSImage` does not store all frames in memory.
@note Note that because of the limitations of category this property can get out of sync if you create another instance with CGImage or other methods.
@note For custom animated class conforms to `ZYJSDAnimatedImage`, you can override this getter method in your subclass to return a more proper value instead, which representing the current frame's total bytes.
*/
@property (assign, nonatomic) NSUInteger ZYJSD_memoryCost;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "NSData+ZYJImageContentType.h"
/**
UIImage category for image ZYJMetadata, including animation, loop count, format, incremental, etc.
*/
@interface UIImage (ZYJMetadata)
/**
* UIKit:
* For static image format, this value is always 0.
* For animated image format, 0 means infinite looping.
* Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods.
* AppKit:
* NSImage currently only support animated via GIF imageRep unlike UIImage.
* The getter of this property will get the loop count from GIF imageRep
* The setter of this property will set the loop count from GIF imageRep
*/
@property (nonatomic, assign) NSUInteger ZYJSD_imageLoopCount;
/**
* UIKit:
* Check the `images` array property.
* AppKit:
* NSImage currently only support animated via GIF imageRep unlike UIImage. It will check the imageRep's frame count.
*/
@property (nonatomic, assign, readonly) BOOL ZYJSD_isAnimated;
/**
* UIKit:
* Check the `isSymbolImage` property. Also check the system PDF(iOS 11+) && SVG(iOS 13+) support.
* AppKit:
* NSImage supports PDF && SVG && EPS imageRep, check the imageRep class.
*/
@property (nonatomic, assign, readonly) BOOL ZYJSD_isVector;
/**
* The image format represent the original compressed image data format.
* If you don't manually specify a format, this information is retrieve from CGImage using `CGImageGetUTType`, which may return nil for non-CG based image. At this time it will return `ZYJSDImageFormatUndefined` as default value.
* @note Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods.
*/
@property (nonatomic, assign) ZYJSDImageFormat ZYJSD_imageFormat;
/**
A bool value indicating whether the image is during incremental decoding and may not contains full pixels.
*/
@property (nonatomic, assign) BOOL ZYJSD_isIncremental;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "NSData+ZYJImageContentType.h"
/**
UIImage category for convenient image format decoding/encoding.
*/
@interface UIImage (ZYJMultiFormat)
#pragma mark - Decode
/**
Create and decode a image with the specify image data
@param data The image data
@return The created image
*/
+ (nullable UIImage *)ZYJSD_imageWithData:(nullable NSData *)data;
/**
Create and decode a image with the specify image data and scale
@param data The image data
@param scale The image scale factor. Should be greater than or equal to 1.0.
@return The created image
*/
+ (nullable UIImage *)ZYJSD_imageWithData:(nullable NSData *)data scale:(CGFloat)scale;
/**
Create and decode a image with the specify image data and scale, allow specify animate/static control
@param data The image data
@param scale The image scale factor. Should be greater than or equal to 1.0.
@param firstFrameOnly Even if the image data is animated image format, decode the first frame only as static image.
@return The created image
*/
+ (nullable UIImage *)ZYJSD_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly;
#pragma mark - Encode
/**
Encode the current image to the data, the image format is unspecified
@note If the receiver is `ZYJSDAnimatedImage`, this will return the animated image data if available. No more extra encoding process.
@return The encoded data. If can't encode, return nil
*/
- (nullable NSData *)ZYJSD_imageData;
/**
Encode the current image to data with the specify image format
@param imageFormat The specify image format
@return The encoded data. If can't encode, return nil
*/
- (nullable NSData *)ZYJSD_imageDataAsFormat:(ZYJSDImageFormat)imageFormat NS_SWIFT_NAME(ZYJSD_imageData(as:));
/**
Encode the current image to data with the specify image format and compression quality
@param imageFormat The specify image format
@param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality.
@return The encoded data. If can't encode, return nil
*/
- (nullable NSData *)ZYJSD_imageDataAsFormat:(ZYJSDImageFormat)imageFormat compressionQuality:(double)compressionQuality NS_SWIFT_NAME(ZYJSD_imageData(as:compressionQuality:));
/**
Encode the current image to data with the specify image format and compression quality, allow specify animate/static control
@param imageFormat The specify image format
@param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality.
@param firstFrameOnly Even if the image is animated image, encode the first frame only as static image.
@return The encoded data. If can't encode, return nil
*/
- (nullable NSData *)ZYJSD_imageDataAsFormat:(ZYJSDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly NS_SWIFT_NAME(ZYJSD_imageData(as:compressionQuality:firstFrameOnly:));
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NS_ENUM(NSUInteger, ZYJSDImageScaleMode) {
ZYJSDImageScaleModeFill = 0,
ZYJSDImageScaleModeAspectFit = 1,
ZYJSDImageScaleModeAspectFill = 2
};
#if ZYJSD_UIKIT || ZYJSD_WATCH
typedef UIRectCorner ZYJSDRectCorner;
#else
typedef NS_OPTIONS(NSUInteger, ZYJSDRectCorner) {
ZYJSDRectCornerTopLeft = 1 << 0,
ZYJSDRectCornerTopRight = 1 << 1,
ZYJSDRectCornerBottomLeft = 1 << 2,
ZYJSDRectCornerBottomRight = 1 << 3,
ZYJSDRectCornerAllCorners = ~0UL
};
#endif
/**
Provide some common method for `UIImage`.
Image process is based on Core Graphics and vImage.
*/
@interface UIImage (ZYJTransform)
#pragma mark - Image Geometry
/**
Returns a new image which is resized from this image.
You can specify a larger or smaller size than the image size. The image content will be changed with the scale mode.
@param size The new size to be resized, values should be positive.
@param scaleMode The scale mode for image content.
@return The new image with the given size.
*/
- (nullable UIImage *)ZYJSD_resizedImageWithSize:(CGSize)size scaleMode:(ZYJSDImageScaleMode)scaleMode;
/**
Returns a new image which is cropped from this image.
@param rect Image's inner rect.
@return The new image with the cropping rect.
*/
- (nullable UIImage *)ZYJSD_croppedImageWithRect:(CGRect)rect;
/**
Rounds a new image with a given corner radius and corners.
@param cornerRadius 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.
@param corners 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.
@param borderWidth The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
@param borderColor The border stroke color. nil means clear color.
@return The new image with the round corner.
*/
- (nullable UIImage *)ZYJSD_roundedCornerImageWithRadius:(CGFloat)cornerRadius
corners:(ZYJSDRectCorner)corners
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor;
/**
Returns a new rotated image (relative to the center).
@param angle Rotated radians in counterclockwise.⟲
@param fitSize YES: new image's size is extend to fit all content.
NO: image's size will not change, content may be clipped.
@return The new image with the rotation.
*/
- (nullable UIImage *)ZYJSD_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize;
/**
Returns a new horizontally(vertically) flipped image.
@param horizontal YES to flip the image horizontally. ⇋
@param vertical YES to flip the image vertically. ⥯
@return The new image with the flipping.
*/
- (nullable UIImage *)ZYJSD_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical;
#pragma mark - Image Blending
/**
Return a tinted image with the given color. This actually use alpha blending of current image and the tint color.
@param tintColor The tint color.
@return The new image with the tint color.
*/
- (nullable UIImage *)ZYJSD_tintedImageWithColor:(nonnull UIColor *)tintColor;
/**
Return the pixel color at specify position. The point is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based.
@note The point's x/y should not be smaller than 0, or greater than or equal to width/height.
@note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself.
@param point The position of pixel
@return The color for specify pixel, or nil if any error occur
*/
- (nullable UIColor *)ZYJSD_colorAtPoint:(CGPoint)point;
/**
Return the pixel color array with specify rectangle. The rect is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based.
@note The rect's width/height should not be smaller than or equal to 0. The minX/minY should not be smaller than 0. The maxX/maxY should not be greater than width/height. Attention this limit is different from `ZYJSD_colorAtPoint:` (point: (0, 0) like rect: (0, 0, 1, 1))
@note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself.
@param rect The rectangle of pixels
@return The color array for specify pixels, or nil if any error occur
*/
- (nullable NSArray<UIColor *> *)ZYJSD_colorsWithRect:(CGRect)rect;
#pragma mark - Image Effect
/**
Return a new image applied a blur effect.
@param blurRadius The radius of the blur in points, 0 means no blur effect.
@return The new image with blur effect, or nil if an error occurs (e.g. no enough memory).
*/
- (nullable UIImage *)ZYJSD_blurredImageWithRadius:(CGFloat)blurRadius;
#if ZYJSD_UIKIT || ZYJSD_MAC
/**
Return a new image applied a CIFilter.
@param filter The CIFilter to be applied to the image.
@return The new image with the CIFilter, or nil if an error occurs (e.g. no
enough memory).
*/
- (nullable UIImage *)ZYJSD_filteredImageWithFilter:(nonnull CIFilter *)filter;
#endif
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImage.h"
// This category is just use as a convenience method. For more detail control, use methods in `UIImage+ZYJMultiFormat.h` or directlly use `ZYJSDImageCoder`
@interface UIImage (ZYJWebP)
/**
Create a image from the WebP data.
This will create animated image if the data is Animated WebP. And will create a static image is the data is Static WebP.
@param data The WebP data
@return The created image
*/
+ (nullable UIImage *)ZYJSD_imageWithWebPData:(nullable NSData *)data;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#if ZYJSD_UIKIT
#import "ZYJSDWebImageManager.h"
/**
* Integrates ZYJSDWebImage async downloading and caching of remote images with UIImageView for highlighted state.
*/
@interface UIImageView (HighlightedZYJWebCache)
/**
* Set the imageView `highlightedImage` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see ZYJSDWebImageOptions for the possible values.
*/
- (void)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
options:(ZYJSDWebImageOptions)options NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `highlightedImage` with an `url`, custom options and context.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context;
/**
* Set the imageView `highlightedImage` 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)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see ZYJSDWebImageOptions 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)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
options:(ZYJSDWebImageOptions)options
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see ZYJSDWebImageOptions 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)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
options:(ZYJSDWebImageOptions)options
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
/**
* Set the imageView `highlightedImage` with an `url`, custom options and context.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. 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)ZYJSD_setHighlightedImageWithURL:(nullable NSURL *)url
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDWebImageManager.h"
/**
* Usage with a UITableViewCell sub-class:
*
* @code
#import "UIImageView+ZYJWebCache.h"
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
// Here we use the provided ZYJSD_setImageWithURL:placeholderImage: method to load the web image
// Ensure you use a placeholder image otherwise cells will be initialized with no image
[cell.imageView ZYJSD_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder"]];
cell.textLabel.text = @"My Text";
return cell;
}
* @endcode
*/
/**
* Integrates ZYJSDWebImage async downloading and caching of remote images with UIImageView.
*/
@interface UIImageView (ZYJWebCache)
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)ZYJSD_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 ZYJSD_setImageWithURL:placeholderImage:options:
*/
- (void)ZYJSD_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 ZYJSDWebImageOptions for the possible values.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
completed:(nullable ZYJSDExternalCompletionBlock)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDWebImageDefine.h"
#import "ZYJSDWebImageManager.h"
#import "ZYJSDWebImageTransition.h"
#import "ZYJSDWebImageIndicator.h"
/**
The value specify that the image progress unit count cannot be determined because the progressBlock is not been called.
*/
FOUNDATION_EXPORT const int64_t ZYJSDWebImageProgressUnitCountUnknown; /* 1LL */
typedef void(^ZYJSDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData, ZYJSDImageCacheType cacheType, NSURL * _Nullable imageURL);
/**
Integrates ZYJSDWebImage async downloading and caching of remote images with UIView subclass.
*/
@interface UIView (ZYJWebCache)
/**
* Get the current image URL.
*
* @note Note that because of the limitations of categories this property can get out of sync if you use setImage: directly.
*/
@property (nonatomic, strong, readonly, nullable) NSURL *ZYJSD_imageURL;
/**
* Get the current image operation key. Operation key is used to identify the different queries for one view instance (like UIButton).
* See more about this in `ZYJSDWebImageContextSetImageOperationKey`.
* If you cancel current image load, the key will be set to nil.
* @note You can use method `UIView+ZYJWebCacheOperation` to investigate different queries' operation.
*/
@property (nonatomic, strong, readonly, nullable) NSString *ZYJSD_latestOperationKey;
/**
* The current image loading progress associated to the view. The unit count is the received size and excepted size of download.
* The `totalUnitCount` and `completedUnitCount` will be reset to 0 after a new image loading start (change from current queue). And they will be set to `ZYJSDWebImageProgressUnitCountUnknown` if the progressBlock not been called but the image loading success to mark the progress finished (change from main queue).
* @note You can use Key-Value Observing on the progress, but you should take care that the change to progress is from a background queue during download(the same as progressBlock). If you want to using KVO and update the UI, make sure to dispatch on the main queue. And it's recommend to use some KVO libs like KVOController because it's more safe and easy to use.
* @note The getter will create a progress instance if the value is nil. But by default, we don't create one. If you need to use Key-Value Observing, you must trigger the getter or set a custom progress instance before the loading start. The default value is nil.
* @note Note that because of the limitations of categories this property can get out of sync if you update the progress directly.
*/
@property (nonatomic, strong, null_resettable) NSProgress *ZYJSD_imageProgress;
/**
* Set the imageView `image` with an `url` and optionally a placeholder image.
*
* 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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param setImageBlock Block used for custom set image code. If not provide, use the built-in set image code (supports `UIImageView/NSImageView` and `UIButton/NSButton` currently)
* @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 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 `ZYJSDImageCacheType` enum indicating if the image was retrieved from the local cache
* or from the memory cache or from the network.
*
* The fifth parameter normally is always YES. However, if you provide ZYJSDWebImageAvoidAutoSetImage with ZYJSDWebImageProgressiveLoad options to enable progressive downloading and set the image yourself. 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
*/
- (void)ZYJSD_internalSetImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
setImageBlock:(nullable ZYJSDSetImageBlock)setImageBlock
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDInternalCompletionBlock)completedBlock;
/**
* Cancel the current image load
*/
- (void)ZYJSD_cancelCurrentImageLoad;
#if ZYJSD_UIKIT || ZYJSD_MAC
#pragma mark - Image Transition
/**
The image transition when image load finished. See `ZYJSDWebImageTransition`.
If you specify nil, do not do transition. Defaults to nil.
*/
@property (nonatomic, strong, nullable) ZYJSDWebImageTransition *ZYJSD_imageTransition;
#pragma mark - Image Indicator
/**
The image indicator during the image loading. If you do not need indicator, specify nil. Defaults to nil
The setter will remove the old indicator view and add new indicator view to current view's subview.
@note Because this is UI related, you should access only from the main queue.
*/
@property (nonatomic, strong, nullable) id<ZYJSDWebImageIndicator> ZYJSD_imageIndicator;
#endif
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDWebImageOperation.h"
/**
These methods are used to support canceling for UIView image loading, it's designed to be used internal but not external.
All the stored operations are weak, so it will be dealloced after image loading finished. If you need to store operations, use your own class to keep a strong reference for them.
*/
@interface UIView (ZYJWebCacheOperation)
/**
* Get the image load operation for key
*
* @param key key for identifying the operations
* @return the image load operation
*/
- (nullable id<ZYJSDWebImageOperation>)ZYJSD_imageLoadOperationForKey:(nullable NSString *)key;
/**
* Set the image load operation (storage in a UIView based weak map table)
*
* @param operation the operation
* @param key key for storing the operation
*/
- (void)ZYJSD_setImageLoadOperation:(nullable id<ZYJSDWebImageOperation>)operation forKey:(nullable NSString *)key;
/**
* Cancel all operations for the current UIView and key
*
* @param key key for identifying the operations
*/
- (void)ZYJSD_cancelImageLoadOperationWithKey:(nullable NSString *)key;
/**
* Just remove the operations corresponding to the current UIView and key without cancelling them
*
* @param key key for identifying the operations
*/
- (void)ZYJSD_removeImageLoadOperationWithKey:(nullable NSString *)key;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDImageCoder.h"
/**
This is the protocol for ZYJSDAnimatedImage class only but not for ZYJSDAnimatedImageCoder. 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 ZYJSDAnimatedImage <ZYJSDAnimatedImageProvider>
@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 ZYJSDImageCoderOptions *)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 `ZYJSDProgressiveImageCoder` for progressive animation decoding.
@param animatedCoder An animated coder which conform `ZYJSDAnimatedImageCoder` 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<ZYJSDAnimatedImageCoder>)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 `ZYJSDProgressiveImageCoder` for progressive animation decoding.
*/
@property (nonatomic, strong, readonly, nullable) id<ZYJSDAnimatedImageCoder> animatedCoder;
@end
/**
The image class which supports animating on `ZYJSDAnimatedImageView`. You can also use it on normal UIImageView/NSImageView.
*/
@interface ZYJSDAnimatedImage : UIImage <ZYJSDAnimatedImage>
// 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.
// Pay attention, when the animated image frame count <= 1, all the `ZYJSDAnimatedImageProvider` 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>)
+ (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.
*/
@property (nonatomic, assign, readonly) ZYJSDImageFormat 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 `ZYJSDAnimatedImage` 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.
- (void)preloadAllFrames;
- (void)unloadAllFrames;
@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDImageCoder.h"
typedef NS_ENUM(NSUInteger, ZYJSDAnimatedImagePlaybackMode) {
/**
* From first to last frame and stop or next loop.
*/
ZYJSDAnimatedImagePlaybackModeNormal = 0,
/**
* From last frame to first frame and stop or next loop.
*/
ZYJSDAnimatedImagePlaybackModeReverse,
/**
* From first frame to last frame and reverse again, like reciprocating.
*/
ZYJSDAnimatedImagePlaybackModeBounce,
/**
* From last frame to first frame and reverse again, like reversed reciprocating.
*/
ZYJSDAnimatedImagePlaybackModeReversedBounce,
};
/// 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 ZYJSDAnimatedImagePlayer : 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 ZYJSDAnimatedImagePlaybackModeNormal.
@property (nonatomic, assign) ZYJSDAnimatedImagePlaybackMode 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, NZYJSDefaultRunLoopMode 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 `ZYJSDAnimatedImage`, `ZYJSDImageGIFCoder`, 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<ZYJSDAnimatedImageProvider>)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 `ZYJSDAnimatedImage` or `ZYJSDImageGIFCoder`, 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<ZYJSDAnimatedImageProvider>)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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#if ZYJSD_MAC
/**
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 `ZYJSDImageIOCoder`, which just call `NSImage` API and actually use `NSBitmapImageRep` for GIF image.
This also support APNG format using `ZYJSDImageAPNGCoder`. Which provide full alpha-channel support and the correct duration match the `kCGImagePropertyAPNGUnclampedDelayTime`.
*/
@interface ZYJSDAnimatedImageRep : NSBitmapImageRep
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDAnimatedImageView.h"
#if ZYJSD_UIKIT || ZYJSD_MAC
#import "ZYJSDWebImageManager.h"
/**
Integrates ZYJSDWebImage async downloading and caching of remote images with ZYJSDAnimatedImageView.
*/
@interface ZYJSDAnimatedImageView (ZYJWebCache)
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)ZYJSD_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 ZYJSD_setImageWithURL:placeholderImage:options:
*/
- (void)ZYJSD_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 ZYJSDWebImageOptions for the possible values.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
*/
- (void)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
completed:(nullable ZYJSDExternalCompletionBlock)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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)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 ZYJSDWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `ZYJSDWebImageContextOption`. 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)ZYJSD_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
progress:(nullable ZYJSDImageLoaderProgressBlock)progressBlock
completed:(nullable ZYJSDExternalCompletionBlock)completedBlock;
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#if ZYJSD_UIKIT || ZYJSD_MAC
#import "ZYJSDAnimatedImage.h"
#import "ZYJSDAnimatedImagePlayer.h"
/**
A drop-in replacement for UIImageView/NSImageView, you can use this for animated image rendering.
Call `setImage:` with `UIImage(NSImage)` which conforms to `ZYJSDAnimatedImage` 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.
*/
@interface ZYJSDAnimatedImageView : 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 `ZYJSDAnimatedImageView` may not get synced.
*/
@property (nonatomic, strong, readonly, nullable) ZYJSDAnimatedImagePlayer *player;
/**
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 ZYJSDAnimatedImagePlaybackModeNormal.
@property (nonatomic, assign) ZYJSDAnimatedImagePlaybackMode 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 `ZYJSD_isIncremental` is YES (See `UIImage+ZYJMetadata.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 `ZYJSD_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 `ZYJSDAnimatedImage` with animated coder which conform to `ZYJSDProgressiveImageCoder` 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 `ZYJSDAnimatedImage` 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, NZYJSDefaultRunLoopMode on single-core device
@note This is useful for some cases, for example, always specify NZYJSDefaultRunLoopMode, 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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// Copy the associated object from source image to target image. The associated object including all the category read/write properties.
/// @param source source
/// @param target target
FOUNDATION_EXPORT void ZYJSDImageCopyAssociatedObject(UIImage * _Nullable source, UIImage * _Nullable target);
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
@class ZYJSDAsyncBlockOperation;
typedef void (^ZYJSDAsyncBlock)(ZYJSDAsyncBlockOperation * __nonnull asyncOperation);
/// A async block operation, success after you call `completer` (not like `NSBlockOperation` which is for sync block, success on return)
@interface ZYJSDAsyncBlockOperation : NSOperation
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDAsyncBlock)block;
+ (nonnull instancetype)blockOperationWithBlock:(nonnull ZYJSDAsyncBlock)block;
- (void)complete;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// Device information helper methods
@interface ZYJSDDeviceHelper : NSObject
+ (NSUInteger)totalMemory;
+ (NSUInteger)freeMemory;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
@class ZYJSDImageCacheConfig;
/**
A protocol to allow custom disk cache used in ZYJSDImageCache.
*/
@protocol ZYJSDDiskCache <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 ZYJSDImageCacheConfig *)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)containZYJSDataForKey:(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 ZYJSDDiskCache : NSObject <ZYJSDDiskCache>
/**
Cache Config object - storing all kind of settings.
*/
@property (nonatomic, strong, readonly, nonnull) ZYJSDImageCacheConfig *config;
- (nonnull instancetype)init 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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// Cross-platform display link wrapper. Do not retain the target
/// Use `CADisplayLink` on iOS/tvOS, `CVDisplayLink` on macOS, `NSTimer` on watchOS
@interface ZYJSDDisplayLink : NSObject
@property (readonly, nonatomic, weak, nullable) id target;
@property (readonly, nonatomic, assign, nonnull) SEL selector;
@property (readonly, nonatomic) CFTimeInterval duration;
@property (readonly, nonatomic) BOOL isRunning;
+ (nonnull instancetype)displayLinkWithTarget:(nonnull id)target selector:(nonnull SEL)sel;
- (void)addToRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode;
- (void)removeFromRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode;
- (void)start;
- (void)stop;
@end
//
// This file is from https://gist.github.com/zydeco/6292773
//
// Created by Jesús A. Álvarez on 2008-12-17.
// Copyright 2008-2009 namedfork.net. All rights reserved.
//
#import <Foundation/Foundation.h>
/// File Extended Attribute (xattr) helper methods
@interface ZYJSDFileAttributeHelper : NSObject
+ (nullable NSArray<NSString *> *)extendedAttributeNamesAtPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err;
+ (BOOL)hasExtendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err;
+ (nullable NSData *)extendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err;
+ (BOOL)setExtendedAttribute:(nonnull NSString *)name value:(nonnull NSData *)value atPath:(nonnull NSString *)path traverseLink:(BOOL)follow overwrite:(BOOL)overwrite error:(NSError * _Nullable * _Nullable)err;
+ (BOOL)removeExtendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.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 `ZYJSDImageGraphics.h` to implements the same behavior (but without dynamic bitmap support)
*/
typedef void (^ZYJSDGraphicsImageDrawingActions)(CGContextRef _Nonnull context);
typedef NS_ENUM(NSInteger, ZYJSDGraphicsImageRendererFormatRange) {
ZYJSDGraphicsImageRendererFormatRangeUnspecified = -1,
ZYJSDGraphicsImageRendererFormatRangeAutomatic = 0,
ZYJSDGraphicsImageRendererFormatRangeExtended,
ZYJSDGraphicsImageRendererFormatRangeStandard
};
/// A set of drawing attributes that represent the configuration of an image renderer context.
@interface ZYJSDGraphicsImageRendererFormat : NSObject
/// 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) ZYJSDGraphicsImageRendererFormatRange preferredRange;
/// Init the default format. See each properties's default value.
- (nonnull instancetype)init;
/// Returns a new format best suited for the main screen’s current configuration.
+ (nonnull instancetype)preferredFormat;
@end
/// A graphics renderer for creating Core Graphics-backed images.
@interface ZYJSDGraphicsImageRenderer : 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 ZYJSDGraphicsImageRendererFormat object that encapsulates the format used to create the renderer context.
/// @return An initialized image renderer.
- (nonnull instancetype)initWithSize:(CGSize)size format:(nonnull ZYJSDGraphicsImageRendererFormat *)format;
/// Creates an image by following a set of drawing instructions.
/// @param actions A ZYJSDGraphicsImageDrawingActions 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 ZYJSDGraphicsImageDrawingActions)actions;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageIOAnimatedCoder.h"
/**
Built in coder using ImageIO that supports APNG encoding/decoding
*/
@interface ZYJSDImageAPNGCoder : ZYJSDImageIOAnimatedCoder <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageAPNGCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageIOAnimatedCoder.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/ZYJSDWebImage/ZYJSDWebImageWebPCoder
*/
API_AVAILABLE(ios(14.0), tvos(14.0), macos(11.0), watchos(7.0))
@interface ZYJSDImageAWebPCoder : ZYJSDImageIOAnimatedCoder <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageAWebPCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// A Image-Asset manager to work like UIKit/AppKit's image cache behavior
/// Apple parse the Asset Catalog compiled file(`Assets.car`) by CoreUI.framework, however it's a private framework and there are no other ways to directly get the data. So we just process the normal bundle files :)
@interface ZYJSDImageAssetManager : NSObject
@property (nonatomic, strong, nonnull) NSMapTable<NSString *, UIImage *> *imageTable;
+ (nonnull instancetype)sharedAssetManager;
- (nullable NSString *)getPathForName:(nonnull NSString *)name bundle:(nonnull NSBundle *)bundle preferredScale:(nonnull CGFloat *)scale;
- (nullable UIImage *)imageForName:(nonnull NSString *)name;
- (void)storeImage:(nonnull UIImage *)image forName:(nonnull NSString *)name;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// Image Cache Expire Type
typedef NS_ENUM(NSUInteger, ZYJSDImageCacheConfigExpireType) {
/**
* When the image cache is accessed it will update this value
*/
ZYJSDImageCacheConfigExpireTypeAccesZYJSDate,
/**
* When the image cache is created or modified it will update this value (Default)
*/
ZYJSDImageCacheConfigExpireTypeModificationDate,
/**
* When the image cache is created it will update this value
*/
ZYJSDImageCacheConfigExpireTypeCreationDate,
/**
* When the image cache is created, modified, renamed, file attribute updated (like permission, xattr) it will update this value
*/
ZYJSDImageCacheConfigExpireTypeChangeDate,
};
/**
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 ZYJSDImageCacheConfig : NSObject <NSCopying>
/**
Gets the default cache config used for shared instance or initialization when it does not provide any cache config. Such as `ZYJSDImageCache.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) ZYJSDImageCacheConfig *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, `ZYJSDImageCache`'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.
* Defaults to YES. 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 Modified Date
*/
@property (assign, nonatomic) ZYJSDImageCacheConfigExpireType 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 custom memory cache class. Provided class instance must conform to `ZYJSDMemoryCache` protocol to allow usage.
* Defaults to built-in `ZYJSDMemoryCache` 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 `ZYJSDDiskCache` protocol to allow usage.
* Defaults to built-in `ZYJSDDiskCache` 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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDWebImageOperation.h"
#import "ZYJSDWebImageDefine.h"
/// Image Cache Type
typedef NS_ENUM(NSInteger, ZYJSDImageCacheType) {
/**
* 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.
*/
ZYJSDImageCacheTypeNone,
/**
* 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.
*/
ZYJSDImageCacheTypeDisk,
/**
* 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.
*/
ZYJSDImageCacheTypeMemory,
/**
* 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.
*/
ZYJSDImageCacheTypeAll
};
typedef void(^ZYJSDImageCacheCheckCompletionBlock)(BOOL isInCache);
typedef void(^ZYJSDImageCacheQueryDataCompletionBlock)(NSData * _Nullable data);
typedef void(^ZYJSDImageCacheCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
typedef NSString * _Nullable (^ZYJSDImageCacheAdditionalCachePathBlock)(NSString * _Nonnull key);
typedef void(^ZYJSDImageCacheQueryCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, ZYJSDImageCacheType cacheType);
typedef void(^ZYJSDImageCacheContainsCompletionBlock)(ZYJSDImageCacheType 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 ZYJSDWebImage'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 ZYJSDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, ZYJSDWebImageOptions options, ZYJSDWebImageContext * _Nullable context);
/**
This is the image cache protocol to provide custom image cache for `ZYJSDWebImageManager`.
Though the best practice to custom image cache, is to write your own class which conform `ZYJSDMemoryCache` or `ZYJSDDiskCache` protocol for `ZYJSDImageCache` class (See more on `ZYJSDImageCacheConfig.memoryCacheClass & ZYJSDImageCacheConfig.diskCacheClass`).
However, if your own cache implementation contains more advanced feature beyond `ZYJSDImageCache` itself, you can consider to provide this instead. For example, you can even use a cache manager like `ZYJSDImageCachesManager` to register multiple caches.
*/
@protocol ZYJSDImageCache <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 `ZYJSDWebImageQueryDiskSync`)
@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 `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@param completionBlock The completion block. Will not get called if the operation is cancelled
@return The operation for this query
*/
- (nullable id<ZYJSDWebImageOperation>)queryImageForKey:(nullable NSString *)key
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
completion:(nullable ZYJSDImageCacheQueryCompletionBlock)completionBlock;
/**
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 `ZYJSDWebImageQueryDiskSync`)
@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 `ZYJSDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
@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<ZYJSDWebImageOperation>)queryImageForKey:(nullable NSString *)key
options:(ZYJSDWebImageOptions)options
context:(nullable ZYJSDWebImageContext *)context
cacheType:(ZYJSDImageCacheType)cacheType
completion:(nullable ZYJSDImageCacheQueryCompletionBlock)completionBlock;
/**
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:(ZYJSDImageCacheType)cacheType
completion:(nullable ZYJSDWebImageNoParamsBlock)completionBlock;
/**
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:(ZYJSDImageCacheType)cacheType
completion:(nullable ZYJSDWebImageNoParamsBlock)completionBlock;
/**
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:(ZYJSDImageCacheType)cacheType
completion:(nullable ZYJSDImageCacheContainsCompletionBlock)completionBlock;
/**
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:(ZYJSDImageCacheType)cacheType
completion:(nullable ZYJSDWebImageNoParamsBlock)completionBlock;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageCacheDefine.h"
/// Policy for cache operation
typedef NS_ENUM(NSUInteger, ZYJSDImageCachesManagerOperationPolicy) {
ZYJSDImageCachesManagerOperationPolicySerial, // process all caches serially (from the highest priority to the lowest priority cache by order)
ZYJSDImageCachesManagerOperationPolicyConcurrent, // process all caches concurrently
ZYJSDImageCachesManagerOperationPolicyHighestOnly, // process the highest priority cache only
ZYJSDImageCachesManagerOperationPolicyLowestOnly // process the lowest priority cache only
};
/**
A caches manager to manage multiple caches.
*/
@interface ZYJSDImageCachesManager : NSObject <ZYJSDImageCache>
/**
Returns the global shared caches manager instance. By default we will set [`ZYJSDImageCache.sharedImageCache`] into the caches array.
*/
@property (nonatomic, class, readonly, nonnull) ZYJSDImageCachesManager *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) ZYJSDImageCachesManagerOperationPolicy queryOperationPolicy;
/**
Operation policy for store op.
Defaults to `HighestOnly`, means store to the highest priority cache only.
*/
@property (nonatomic, assign) ZYJSDImageCachesManagerOperationPolicy storeOperationPolicy;
/**
Operation policy for remove op.
Defaults to `Concurrent`, means remove all caches concurrently.
*/
@property (nonatomic, assign) ZYJSDImageCachesManagerOperationPolicy 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) ZYJSDImageCachesManagerOperationPolicy containsOperationPolicy;
/**
Operation policy for clear op.
Defaults to `Concurrent`, means clear all caches concurrently.
*/
@property (nonatomic, assign) ZYJSDImageCachesManagerOperationPolicy 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<ZYJSDImageCache>> *caches;
/**
Add a new cache to the end of caches array. Which has the highest priority.
@param cache cache
*/
- (void)addCache:(nonnull id<ZYJSDImageCache>)cache;
/**
Remove a cache in the caches array.
@param cache cache
*/
- (void)removeCache:(nonnull id<ZYJSDImageCache>)cache;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// This is used for operation management, but not for operation queue execute
@interface ZYJSDImageCachesManagerOperation : NSOperation
@property (nonatomic, assign, readonly) NSUInteger pendingCount;
- (void)beginWithTotalCount:(NSUInteger)totalCount;
- (void)completeOne;
- (void)done;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "ZYJSDImageFrame.h"
/**
Provide some common helper methods for building the image decoder/encoder.
*/
@interface ZYJSDImageCoderHelper : 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<ZYJSDImageFrame *> * _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<ZYJSDImageFrame *> * _Nullable)framesFromAnimatedImage:(UIImage * _Nullable)animatedImage NS_SWIFT_NAME(frames(from:));
/**
Return the shared device-dependent RGB color space. This follows The Get Rule.
On iOS, it's created with deviceRGB (if available, use sRGB).
On macOS, it's from the screen colorspace (if failed, use deviceRGB)
Because it's shared, you should not retain or release this object.
@return The device-dependent RGB color space
*/
+ (CGColorSpaceRef _Nonnull)colorSpaceGetDeviceRGB CF_RETURNS_NOT_RETAINED;
/**
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;
/**
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.
@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;
/**
Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image
@param image The image to be decoded
@return The decoded image
*/
+ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image;
/**
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.
@return The decoded and probably scaled down image
*/
+ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes;
/**
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 ZYJSD_UIKIT || ZYJSD_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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageCoder.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 `ZYJSDImageCoder` protocol or even to `ZYJSDProgressiveImageCoder` 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 ZYJSDImageCodersManager : NSObject <ZYJSDImageCoder>
/**
Returns the global shared coders manager instance.
*/
@property (nonatomic, class, readonly, nonnull) ZYJSDImageCodersManager *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<ZYJSDImageCoder>> *coders;
/**
Add a new coder to the end of coders array. Which has the highest priority.
@param coder coder
*/
- (void)addCoder:(nonnull id<ZYJSDImageCoder>)coder;
/**
Remove a coder in the coders array.
@param coder coder
*/
- (void)removeCoder:(nonnull id<ZYJSDImageCoder>)coder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/**
This class is used for creating animated images via `animatedImageWithFrames` in `ZYJSDImageCoderHelper`.
@note If you need to specify animated images loop count, use `ZYJSD_imageLoopCount` property in `UIImage+ZYJMetadata.h`.
*/
@interface ZYJSDImageFrame : 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
@return frame instance
*/
+ (instancetype _Nonnull)frameWithImage:(UIImage * _Nonnull)image duration:(NSTimeInterval)duration;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageIOAnimatedCoder.h"
/**
Built in coder using ImageIO that supports animated GIF encoding/decoding
@note `ZYJSDImageIOCoder` supports GIF but only as static (will use the 1st frame).
@note Use `ZYJSDImageGIFCoder` for fully animated GIFs. For `UIImageView`, it will produce animated `UIImage`(`NSImage` on macOS) for rendering. For `ZYJSDAnimatedImageView`, it will use `ZYJSDAnimatedImage` for rendering.
@note The recommended approach for animated GIFs is using `ZYJSDAnimatedImage` with `ZYJSDAnimatedImageView`. It's more performant than `UIImageView` for GIF displaying(especially on memory usage)
*/
@interface ZYJSDImageGIFCoder : ZYJSDImageIOAnimatedCoder <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageGIFCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.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 `ZYJSDGraphicsImageRenderer` instead. It's more performant on RAM usage.`
*/
/// Returns the current graphics context.
FOUNDATION_EXPORT CGContextRef __nullable ZYJSDGraphicsGetCurrentContext(void) CF_RETURNS_NOT_RETAINED;
/// Creates a bitmap-based graphics context and makes it the current context.
FOUNDATION_EXPORT void ZYJSDGraphicsBeginImageContext(CGSize size);
/// Creates a bitmap-based graphics context with the specified options.
FOUNDATION_EXPORT void ZYJSDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
/// Removes the current bitmap-based graphics context from the top of the stack.
FOUNDATION_EXPORT void ZYJSDGraphicsEndImageContext(void);
/// Returns an image based on the contents of the current bitmap-based graphics context.
FOUNDATION_EXPORT UIImage * __nullable ZYJSDGraphicsGetImageFromCurrentImageContext(void);
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageIOAnimatedCoder.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/ZYJSDWebImage/ZYJSDWebImageHEIFCoder
*/
API_AVAILABLE(ios(13.0), tvos(13.0), macos(10.15), watchos(6.0))
@interface ZYJSDImageHEICCoder : ZYJSDImageIOAnimatedCoder <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageHEICCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 <ImageIO/ImageIO.h>
#import "ZYJSDImageCoder.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 ZYJSDImageIOAnimatedCoder : NSObject <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
#pragma mark - Subclass Override
/**
The supported animated image format. Such as `ZYJSDImageFormatGIF`.
@note Subclass override.
*/
@property (class, readonly) ZYJSDImageFormat imageFormat;
/**
The supported image format UTI Type. Such as `kUTTypeGIF`.
This can be used for cases when we can not detect `ZYJSDImageFormat. Such as progressive decoding's hint format `kCGImageSourceTypeIdentifierHint`.
@note Subclass override.
*/
@property (class, readonly, nonnull) NSString *imageUTType;
/**
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 ZYJMetadata.
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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageIOAnimatedCoder.h"
// AVFileTypeHEIC/AVFileTypeHEIF is defined in AVFoundation via iOS 11, we use this without import AVFoundation
#define kZYJSDUTTypeHEIC ((__bridge CFStringRef)@"public.heic")
#define kZYJSDUTTypeHEIF ((__bridge CFStringRef)@"public.heif")
// HEIC Sequence (Animated Image)
#define kZYJSDUTTypeHEICS ((__bridge CFStringRef)@"public.heics")
// kUTTypeWebP seems not defined in public UTI framework, Apple use the hardcode string, we define them :)
#define kZYJSDUTTypeWebP ((__bridge CFStringRef)@"org.webmproject.webp")
@interface ZYJSDImageIOAnimatedCoder ()
+ (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source;
+ (NSUInteger)imageLoopCountWithSource:(nonnull CGImageSourceRef)source;
+ (nullable UIImage *)createFrameAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source scale:(CGFloat)scale preserveAspectRatio:(BOOL)preserveAspectRatio thumbnailSize:(CGSize)thumbnailSize options:(nullable NSDictionary *)options;
+ (BOOL)canEncodeToFormat:(ZYJSDImageFormat)format;
+ (BOOL)canDecodeFromFormat:(ZYJSDImageFormat)format;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageCoder.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 `ZYJSDAnimatedImageView` 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 ZYJSDImageIOCoder : NSObject <ZYJSDProgressiveImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageIOCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDImageLoader.h"
/**
A loaders manager to manage multiple loaders
*/
@interface ZYJSDImageLoadersManager : NSObject <ZYJSDImageLoader>
/**
Returns the global shared loaders manager instance. By default we will set [`ZYJSDWebImageDownloader.sharedDownloader`] into the loaders array.
*/
@property (nonatomic, class, readonly, nonnull) ZYJSDImageLoadersManager *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<ZYJSDImageLoader>>* loaders;
/**
Add a new image loader to the end of loaders array. Which has the highest priority.
@param loader loader
*/
- (void)addLoader:(nonnull id<ZYJSDImageLoader>)loader;
/**
Remove an image loader in the loaders array.
@param loader loader
*/
- (void)removeLoader:(nonnull id<ZYJSDImageLoader>)loader;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImage.h"
#import "ZYJSDImageCoder.h"
/**
Built in coder that supports WebP and animated WebP
*/
@interface ZYJSDImageWebPCoder : NSObject <ZYJSDProgressiveImageCoder, ZYJSDAnimatedImageCoder>
@property (nonatomic, class, readonly, nonnull) ZYJSDImageWebPCoder *sharedCoder;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
#import "UIImage+ZYJTransform.h"
/**
Return the ZYJTransformed cache key which applied with specify ZYJTransformerKey.
@param key The original cache key
@param ZYJTransformerKey The ZYJTransformer key from the ZYJTransformer
@return The ZYJTransformed cache key
*/
FOUNDATION_EXPORT NSString * _Nullable ZYJSDZYJTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull ZYJTransformerKey);
/**
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 ZYJTransformer and thumbnail applied for image, call `ZYJSDThumbnailedKeyForKey` firstly and then with `ZYJSDZYJTransformedKeyForKey`.`
*/
FOUNDATION_EXPORT NSString * _Nullable ZYJSDThumbnailedKeyForKey(NSString * _Nullable key, CGSize thumbnailPixelSize, BOOL preserveAspectRatio);
/**
A ZYJTransformer protocol to ZYJTransform the image load from cache or from download.
You can provide ZYJTransformer to cache and manager (Through the `ZYJTransformer` property or context option `ZYJSDWebImageContextImageZYJTransformer`).
@note The ZYJTransform process is called from a global queue in order to not to block the main queue.
*/
@protocol ZYJSDImageZYJTransformer <NSObject>
@required
/**
For each ZYJTransformer, 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.
@return The cache key to appended after the original cache key. Should not be nil.
*/
@property (nonatomic, copy, readonly, nonnull) NSString *ZYJTransformerKey;
/**
ZYJTransform the image to another image.
@param image The image to be ZYJTransformed
@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 ZYJTransformed image, or nil if ZYJTransform failed
*/
- (nullable UIImage *)ZYJTransformedImageWithImage:(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 ZYJTransformer. Which you can bind multiple ZYJTransformers together to let the image to be ZYJTransformed one by one in order and generate the final image.
@note Because ZYJTransformers are lightweight, if you want to append or arrange ZYJTransformers, create another pipeline ZYJTransformer instead. This class is considered as immutable.
*/
@interface ZYJSDImagePipelineZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
All ZYJTransformers in pipeline
*/
@property (nonatomic, copy, readonly, nonnull) NSArray<id<ZYJSDImageZYJTransformer>> *ZYJTransformers;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)ZYJTransformerWithZYJTransformers:(nonnull NSArray<id<ZYJSDImageZYJTransformer>> *)ZYJTransformers;
@end
// There are some built-in ZYJTransformers based on the `UIImage+ZYJTransformer` category to provide the common image geometry, image blending and image effect process. Those ZYJTransform are useful for static image only but you can create your own to support animated image as well.
// Because ZYJTransformers are lightweight, these class are considered as immutable.
#pragma mark - Image Geometry
/**
Image round corner ZYJTransformer
*/
@interface ZYJSDImageRoundCornerZYJTransformer: NSObject <ZYJSDImageZYJTransformer>
/**
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) ZYJSDRectCorner 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)ZYJTransformerWithRadius:(CGFloat)cornerRadius corners:(ZYJSDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor;
@end
/**
Image resizing ZYJTransformer
*/
@interface ZYJSDImageResizingZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
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) ZYJSDImageScaleMode scaleMode;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)ZYJTransformerWithSize:(CGSize)size scaleMode:(ZYJSDImageScaleMode)scaleMode;
@end
/**
Image cropping ZYJTransformer
*/
@interface ZYJSDImageCroppingZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
Image's inner rect.
*/
@property (nonatomic, assign, readonly) CGRect rect;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)ZYJTransformerWithRect:(CGRect)rect;
@end
/**
Image flipping ZYJTransformer
*/
@interface ZYJSDImageFlippingZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
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)ZYJTransformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical;
@end
/**
Image rotation ZYJTransformer
*/
@interface ZYJSDImageRotationZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
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)ZYJTransformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize;
@end
#pragma mark - Image Blending
/**
Image tint color ZYJTransformer
*/
@interface ZYJSDImageTintZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
The tint color.
*/
@property (nonatomic, strong, readonly, nonnull) UIColor *tintColor;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)ZYJTransformerWithColor:(nonnull UIColor *)tintColor;
@end
#pragma mark - Image Effect
/**
Image blur effect ZYJTransformer
*/
@interface ZYJSDImageBlurZYJTransformer : NSObject <ZYJSDImageZYJTransformer>
/**
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)ZYJTransformerWithRadius:(CGFloat)blurRadius;
@end
#if ZYJSD_UIKIT || ZYJSD_MAC
/**
Core Image filter ZYJTransformer
*/
@interface ZYJSDImageFilterZYJTransformer: NSObject <ZYJSDImageZYJTransformer>
/**
The CIFilter to be applied to the image.
*/
@property (nonatomic, strong, readonly, nonnull) CIFilter *filter;
- (nonnull instancetype)init NS_UNAVAILABLE;
+ (nonnull instancetype)ZYJTransformerWithFilter:(nonnull CIFilter *)filter;
@end
#endif
/*
* This file is part of the ZYJSDWebImage 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 <os/lock.h>
#import <libkern/OSAtomic.h>
#import "ZYJSDmetamacros.h"
#define ZYJSD_USE_OS_UNFAIR_LOCK TARGET_OS_MACCATALYST ||\
(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_10_0) ||\
(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_12) ||\
(__TV_OS_VERSION_MIN_REQUIRED >= __TVOS_10_0) ||\
(__WATCH_OS_VERSION_MIN_REQUIRED >= __WATCHOS_3_0)
#ifndef ZYJSD_LOCK_DECLARE
#if ZYJSD_USE_OS_UNFAIR_LOCK
#define ZYJSD_LOCK_DECLARE(lock) os_unfair_lock lock
#else
#define ZYJSD_LOCK_DECLARE(lock) os_unfair_lock lock API_AVAILABLE(ios(10.0), tvos(10), watchos(3), macos(10.12)); \
OSSpinLock lock##_deprecated;
#endif
#endif
#ifndef ZYJSD_LOCK_DECLARE_STATIC
#if ZYJSD_USE_OS_UNFAIR_LOCK
#define ZYJSD_LOCK_DECLARE_STATIC(lock) static os_unfair_lock lock
#else
#define ZYJSD_LOCK_DECLARE_STATIC(lock) static os_unfair_lock lock API_AVAILABLE(ios(10.0), tvos(10), watchos(3), macos(10.12)); \
static OSSpinLock lock##_deprecated;
#endif
#endif
#ifndef ZYJSD_LOCK_INIT
#if ZYJSD_USE_OS_UNFAIR_LOCK
#define ZYJSD_LOCK_INIT(lock) lock = OS_UNFAIR_LOCK_INIT
#else
#define ZYJSD_LOCK_INIT(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) lock = OS_UNFAIR_LOCK_INIT; \
else lock##_deprecated = OS_SPINLOCK_INIT;
#endif
#endif
#ifndef ZYJSD_LOCK
#if ZYJSD_USE_OS_UNFAIR_LOCK
#define ZYJSD_LOCK(lock) os_unfair_lock_lock(&lock)
#else
#define ZYJSD_LOCK(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) os_unfair_lock_lock(&lock); \
else OSSpinLockLock(&lock##_deprecated);
#endif
#endif
#ifndef ZYJSD_UNLOCK
#if ZYJSD_USE_OS_UNFAIR_LOCK
#define ZYJSD_UNLOCK(lock) os_unfair_lock_unlock(&lock)
#else
#define ZYJSD_UNLOCK(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) os_unfair_lock_unlock(&lock); \
else OSSpinLockUnlock(&lock##_deprecated);
#endif
#endif
#ifndef ZYJSD_OPTIONS_CONTAINS
#define ZYJSD_OPTIONS_CONTAINS(options, value) (((options) & (value)) == (value))
#endif
#ifndef ZYJSD_CSTRING
#define ZYJSD_CSTRING(str) #str
#endif
#ifndef ZYJSD_NSSTRING
#define ZYJSD_NSSTRING(str) @(ZYJSD_CSTRING(str))
#endif
#ifndef ZYJSD_SEL_SPI
#define ZYJSD_SEL_SPI(name) NSSelectorFromString([NSString stringWithFormat:@"_%@", ZYJSD_NSSTRING(name)])
#endif
#ifndef weakify
#define weakify(...) \
ZYJSD_keywordify \
metamacro_foreach_cxt(ZYJSD_weakify_,, __weak, __VA_ARGS__)
#endif
#ifndef strongify
#define strongify(...) \
ZYJSD_keywordify \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
metamacro_foreach(ZYJSD_strongify_,, __VA_ARGS__) \
_Pragma("clang diagnostic pop")
#endif
#define ZYJSD_weakify_(INDEX, CONTEXT, VAR) \
CONTEXT __typeof__(VAR) metamacro_concat(VAR, _weak_) = (VAR);
#define ZYJSD_strongify_(INDEX, VAR) \
__strong __typeof__(VAR) VAR = metamacro_concat(VAR, _weak_);
#if DEBUG
#define ZYJSD_keywordify autoreleasepool {}
#else
#define ZYJSD_keywordify try {} @catch (...) {}
#endif
#ifndef onExit
#define onExit \
ZYJSD_keywordify \
__strong ZYJSD_cleanupBlock_t metamacro_concat(ZYJSD_exitBlock_, __LINE__) __attribute__((cleanup(ZYJSD_executeCleanupBlock), unused)) = ^
#endif
typedef void (^ZYJSD_cleanupBlock_t)(void);
#if defined(__cplusplus)
extern "C" {
#endif
void ZYJSD_executeCleanupBlock (__strong ZYJSD_cleanupBlock_t *block);
#if defined(__cplusplus)
}
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
@class ZYJSDImageCacheConfig;
/**
A protocol to allow custom memory cache used in ZYJSDImageCache.
*/
@protocol ZYJSDMemoryCache <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 ZYJSDImageCacheConfig *)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 ZYJSDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType> <ZYJSDMemoryCache>
@property (nonatomic, strong, nonnull, readonly) ZYJSDImageCacheConfig *config;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// A weak proxy which forward all the message to the target
@interface ZYJSDWeakProxy : NSProxy
@property (nonatomic, weak, readonly, nullable) id target;
- (nonnull instancetype)initWithTarget:(nonnull id)target;
+ (nonnull instancetype)proxyWithTarget:(nonnull id)target;
@end
/*
* This file is part of the ZYJSDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com"
* (c) Florent Vilmart
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
//! Project version number for ZYJSDWebImage.
FOUNDATION_EXPORT double ZYJSDWebImageVersionNumber;
//! Project version string for ZYJSDWebImage.
FOUNDATION_EXPORT const unsigned char ZYJSDWebImageVersionString[];
#import "ZYJSDImageWebPCoder.h"
#import "ZYJSDWebImageWebPCoderDefine.h"
#import "UIImage+ZYJWebP.h"
#import "ZYJSDWebImageCompat.h"
#import "ZYJSDWebImageManager.h"
#import "ZYJSDWebImageCacheKeyFilter.h"
#import "ZYJSDWebImageCacheSerializer.h"
#import "ZYJSDImageCacheConfig.h"
#import "ZYJSDImageCache.h"
#import "ZYJSDMemoryCache.h"
#import "ZYJSDDiskCache.h"
#import "ZYJSDImageCacheDefine.h"
#import "ZYJSDImageCachesManager.h"
#import "UIView+ZYJWebCache.h"
#import "UIImageView+ZYJWebCache.h"
#import "UIImageView+HighlightedZYJWebCache.h"
#import "ZYJSDWebImageDownloaderConfig.h"
#import "ZYJSDWebImageDownloaderOperation.h"
#import "ZYJSDWebImageDownloaderRequestModifier.h"
#import "ZYJSDWebImageDownloaderResponseModifier.h"
#import "ZYJSDWebImageDownloaderDecryptor.h"
#import "ZYJSDImageLoader.h"
#import "ZYJSDImageLoadersManager.h"
#import "UIButton+ZYJWebCache.h"
#import "ZYJSDWebImagePrefetcher.h"
#import "UIView+ZYJWebCacheOperation.h"
#import "UIImage+ZYJMetadata.h"
#import "UIImage+ZYJMultiFormat.h"
#import "UIImage+ZYJMemoryCacheCost.h"
#import "UIImage+ZYJExtendedCacheData.h"
#import "ZYJSDWebImageOperation.h"
#import "ZYJSDWebImageDownloader.h"
#import "ZYJSDWebImageTransition.h"
#import "ZYJSDWebImageIndicator.h"
#import "ZYJSDImageZYJTransformer.h"
#import "UIImage+ZYJTransform.h"
#import "ZYJSDAnimatedImage.h"
#import "ZYJSDAnimatedImageView.h"
#import "ZYJSDAnimatedImageView+ZYJWebCache.h"
#import "ZYJSDAnimatedImagePlayer.h"
#import "ZYJSDImageCodersManager.h"
#import "ZYJSDImageCoder.h"
#import "ZYJSDImageAPNGCoder.h"
#import "ZYJSDImageGIFCoder.h"
#import "ZYJSDImageIOCoder.h"
#import "ZYJSDImageFrame.h"
#import "ZYJSDImageCoderHelper.h"
#import "ZYJSDImageGraphics.h"
#import "ZYJSDGraphicsImageRenderer.h"
#import "UIImage+ZYJGIF.h"
#import "UIImage+ZYJForceDecode.h"
#import "NSData+ZYJImageContentType.h"
#import "ZYJSDWebImageDefine.h"
#import "ZYJSDWebImageError.h"
#import "ZYJSDWebImageOptionsProcessor.h"
#import "ZYJSDImageIOAnimatedCoder.h"
#import "ZYJSDImageHEICCoder.h"
#import "ZYJSDImageAWebPCoder.h"
// Mac
#import "NSImage+ZYJCompatibility.h"
#import "NSButton+ZYJWebCache.h"
#import "ZYJSDAnimatedImageRep.h"
// MapKit
#import "MKAnnotationView+ZYJWebCache.h"
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NSString * _Nullable(^ZYJSDWebImageCacheKeyFilterBlock)(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 ZYJSDWebImageCacheKeyFilter <NSObject>
- (nullable NSString *)cacheKeyForURL:(nonnull NSURL *)url;
@end
/**
A cache key filter class with block.
*/
@interface ZYJSDWebImageCacheKeyFilter : NSObject <ZYJSDWebImageCacheKeyFilter>
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDWebImageCacheKeyFilterBlock)block;
+ (nonnull instancetype)cacheKeyFilterWithBlock:(nonnull ZYJSDWebImageCacheKeyFilterBlock)block;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NSData * _Nullable(^ZYJSDWebImageCacheSerializerBlock)(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 ZYJSDWebImageCacheSerializer <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
/// @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 ZYJSDWebImageCacheSerializer : NSObject <ZYJSDWebImageCacheSerializer>
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDWebImageCacheSerializerBlock)block;
+ (nonnull instancetype)cacheSerializerWithBlock:(nonnull ZYJSDWebImageCacheSerializerBlock)block;
@end
/*
* This file is part of the ZYJSDWebImage 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 ZYJSDWebImage 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 ZYJSD_MAC 1
#else
#define ZYJSD_MAC 0
#endif
// iOS and tvOS are very similar, UIKit exists on both platforms
// Note: watchOS also has UIKit, but it's very limited
#if TARGET_OS_IOS || TARGET_OS_TV
#define ZYJSD_UIKIT 1
#else
#define ZYJSD_UIKIT 0
#endif
#if TARGET_OS_IOS
#define ZYJSD_IOS 1
#else
#define ZYJSD_IOS 0
#endif
#if TARGET_OS_TV
#define ZYJSD_TV 1
#else
#define ZYJSD_TV 0
#endif
#if TARGET_OS_WATCH
#define ZYJSD_WATCH 1
#else
#define ZYJSD_WATCH 0
#endif
#if ZYJSD_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 ZYJSD_UIKIT
#import <UIKit/UIKit.h>
#endif
#if ZYJSD_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);\
}
#endif
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
/// Operation execution order
typedef NS_ENUM(NSInteger, ZYJSDWebImageDownloaderExecutionOrder) {
/**
* Default value. All download operations will execute in queue style (first-in-first-out).
*/
ZYJSDWebImageDownloaderFIFOExecutionOrder,
/**
* All download operations will execute in stack style (last-in-first-out).
*/
ZYJSDWebImageDownloaderLIFOExecutionOrder
};
/**
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 ZYJSDWebImageDownloaderConfig : NSObject <NSCopying>
/**
Gets the default downloader config used for shared instance or initialization when it does not provide any downloader config. Such as `ZYJSDWebImageDownloader.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) ZYJSDWebImageDownloaderConfig *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 `ZYJSDWebImageDownloaderOperation` as the default
* `NSOperation` to be used each time ZYJSDWebImage constructs a request
* operation to download an image.
* Defaults to nil.
* @note Passing `NSOperation<ZYJSDWebImageDownloaderOperation>` to set as default. Passing `nil` will revert to `ZYJSDWebImageDownloaderOperation`.
*/
@property (nonatomic, assign, nullable) Class operationClass;
/**
* Changes download operations execution order.
* Defaults to `ZYJSDWebImageDownloaderFIFOExecutionOrder`.
*/
@property (nonatomic, assign) ZYJSDWebImageDownloaderExecutionOrder 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 `ZYJSDWebImageErrorInvalidDownloadStatusCode`.
* 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 `ZYJSDWebImageErrorInvalidDownloadContentType`.
* 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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NSData * _Nullable (^ZYJSDWebImageDownloaderDecryptorBlock)(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 ZYJSDWebImageDownloaderDecryptor <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 `ZYJSDWebImageErrorBadImageData`
- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response;
@end
/**
A downloader response modifier class with block.
*/
@interface ZYJSDWebImageDownloaderDecryptor : NSObject <ZYJSDWebImageDownloaderDecryptor>
/// Create the data decryptor with block
/// @param block A block to control decrypt logic
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDWebImageDownloaderDecryptorBlock)block;
/// Create the data decryptor with block
/// @param block A block to control decrypt logic
+ (nonnull instancetype)decryptorWithBlock:(nonnull ZYJSDWebImageDownloaderDecryptorBlock)block;
@end
/// Convenience way to create decryptor for common data encryption.
@interface ZYJSDWebImageDownloaderDecryptor (Conveniences)
/// Base64 Encoded image data decryptor
@property (class, readonly, nonnull) ZYJSDWebImageDownloaderDecryptor *base64Decryptor;
@end
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageDownloader.h"
#import "ZYJSDWebImageOperation.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 `ZYJSDWebImageDownloaderOperation`
@note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods.
*/
@protocol ZYJSDWebImageDownloaderOperation <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@required
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(ZYJSDWebImageDownloaderOptions)options;
- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(ZYJSDWebImageDownloaderOptions)options
context:(nullable ZYJSDWebImageContext *)context;
- (nullable id)addHandlersForProgress:(nullable ZYJSDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable ZYJSDWebImageDownloaderCompletedBlock)completedBlock;
- (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(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
// These operation-level config was inherited from downloader. See `ZYJSDWebImageDownloaderConfig` 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 ZYJSDWebImageDownloader.
*/
@interface ZYJSDWebImageDownloaderOperation : NSOperation <ZYJSDWebImageDownloaderOperation>
/**
* 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(macosx(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 `ZYJSDWebImageErrorInvalidDownloadStatusCode`.
* 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 `ZYJSDWebImageErrorInvalidDownloadContentType`.
* 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) ZYJSDWebImageDownloaderOptions options;
/**
* The context for the receiver.
*/
@property (copy, nonatomic, readonly, nullable) ZYJSDWebImageContext *context;
/**
* Initializes a `ZYJSDWebImageDownloaderOperation` object
*
* @see ZYJSDWebImageDownloaderOperation
*
* @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:(ZYJSDWebImageDownloaderOptions)options;
/**
* Initializes a `ZYJSDWebImageDownloaderOperation` object
*
* @see ZYJSDWebImageDownloaderOperation
*
* @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 `ZYJSDWebImageContextOption`. 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:(ZYJSDWebImageDownloaderOptions)options
context:(nullable ZYJSDWebImageContext *)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 ZYJSDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable ZYJSDWebImageDownloaderCompletedBlock)completedBlock;
/**
* 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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NSURLRequest * _Nullable (^ZYJSDWebImageDownloaderRequestModifierBlock)(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 ZYJSDWebImageDownloaderRequestModifier <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 ZYJSDWebImageDownloaderRequestModifier : NSObject <ZYJSDWebImageDownloaderRequestModifier>
/// Create the request modifier with block
/// @param block A block to control modifier logic
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDWebImageDownloaderRequestModifierBlock)block;
/// Create the request modifier with block
/// @param block A block to control modifier logic
+ (nonnull instancetype)requestModifierWithBlock:(nonnull ZYJSDWebImageDownloaderRequestModifierBlock)block;
@end
/**
A convenient request modifier to provide the HTTP request including HTTP Method, Headers and Body.
*/
@interface ZYJSDWebImageDownloaderRequestModifier (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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
typedef NSURLResponse * _Nullable (^ZYJSDWebImageDownloaderResponseModifierBlock)(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 ZYJSDWebImageDownloaderResponseModifier <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 `ZYJSDWebImageErrorInvalidDownloadResponse`
- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response;
@end
/**
A downloader response modifier class with block.
*/
@interface ZYJSDWebImageDownloaderResponseModifier : NSObject <ZYJSDWebImageDownloaderResponseModifier>
/// Create the response modifier with block
/// @param block A block to control modifier logic
- (nonnull instancetype)initWithBlock:(nonnull ZYJSDWebImageDownloaderResponseModifierBlock)block;
/// Create the response modifier with block
/// @param block A block to control modifier logic
+ (nonnull instancetype)responseModifierWithBlock:(nonnull ZYJSDWebImageDownloaderResponseModifierBlock)block;
@end
/**
A convenient response modifier to provide the HTTP response including HTTP Status Code, Version and Headers.
*/
@interface ZYJSDWebImageDownloaderResponseModifier (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
/*
* This file is part of the ZYJSDWebImage 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 "ZYJSDWebImageCompat.h"
FOUNDATION_EXPORT NSErrorDomain const _Nonnull ZYJSDWebImageErrorDomain;
/// The response instance for invalid download response (NSURLResponse *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull ZYJSDWebImageErrorDownloadResponseKey;
/// The HTTP status code for invalid download response (NSNumber *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull ZYJSDWebImageErrorDownloadStatusCodeKey;
/// The HTTP MIME content type for invalid download response (NSString *)
FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull ZYJSDWebImageErrorDownloadContentTypeKey;
/// ZYJSDWebImage error domain and codes
typedef NS_ERROR_ENUM(ZYJSDWebImageErrorDomain, ZYJSDWebImageError) {
ZYJSDWebImageErrorInvalidURL = 1000, // The URL is invalid, such as nil URL or corrupted URL
ZYJSDWebImageErrorBadImageData = 1001, // The image data can not be decoded to image, or the image data is empty
ZYJSDWebImageErrorCacheNotModified = 1002, // The remote location specify that the cached image is not modified, such as the HTTP response 304 code. It's useful for `ZYJSDWebImageRefreshCached`
ZYJSDWebImageErrorBlackListed = 1003, // The URL is blacklisted because of unrecoverable failure marked by downloader (such as 404), you can use `.retryFailed` option to avoid this
ZYJSDWebImageErrorInvalidDownloadOperation = 2000, // The image download operation is invalid, such as nil operation or unexpected error occur when operation initialized
ZYJSDWebImageErrorInvalidDownloadStatusCode = 2001, // The image download response a invalid status code. You can check the status code in error's userInfo under `ZYJSDWebImageErrorDownloadStatusCodeKey`
ZYJSDWebImageErrorCancelled = 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.
ZYJSDWebImageErrorInvalidDownloadResponse = 2003, // When using response modifier, the modified download response is nil and marked as failed.
ZYJSDWebImageErrorInvalidDownloadContentType = 2004, // The image download response a invalid content type. You can check the MIME content type in error's userInfo under `ZYJSDWebImageErrorDownloadContentTypeKey`
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment