├── .gitignore ├── Demo ├── LCWebImage.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── LCWebImage.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── LCWebImage │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Assets.xcassets │ │ ├── AccentColor.colorset │ │ │ └── Contents.json │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ └── Contents.json │ ├── Base.lproj │ │ ├── LaunchScreen.storyboard │ │ └── Main.storyboard │ ├── Info.plist │ ├── SceneDelegate.h │ ├── SceneDelegate.m │ ├── Vendor │ │ ├── WebP.framework │ │ │ ├── Headers │ │ │ │ ├── config.h │ │ │ │ ├── decode.h │ │ │ │ ├── demux.h │ │ │ │ ├── encode.h │ │ │ │ ├── extras.h │ │ │ │ ├── format_constants.h │ │ │ │ ├── mux.h │ │ │ │ ├── mux_types.h │ │ │ │ └── types.h │ │ │ └── WebP │ │ └── WebP.sh │ ├── ViewController.h │ ├── ViewController.m │ ├── YYImage │ │ ├── YYAnimatedImageView.h │ │ ├── YYAnimatedImageView.m │ │ ├── YYFrameImage.h │ │ ├── YYFrameImage.m │ │ ├── YYImage.h │ │ ├── YYImage.m │ │ ├── YYImageCoder.h │ │ ├── YYImageCoder.m │ │ ├── YYSpriteSheetImage.h │ │ └── YYSpriteSheetImage.m │ └── main.m ├── Podfile ├── Podfile.lock └── Pods │ ├── AFNetworking │ ├── AFNetworking │ │ ├── AFCompatibilityMacros.h │ │ ├── AFHTTPSessionManager.h │ │ ├── AFHTTPSessionManager.m │ │ ├── AFNetworkReachabilityManager.h │ │ ├── AFNetworkReachabilityManager.m │ │ ├── AFSecurityPolicy.h │ │ ├── AFSecurityPolicy.m │ │ ├── AFURLRequestSerialization.h │ │ ├── AFURLRequestSerialization.m │ │ ├── AFURLResponseSerialization.h │ │ ├── AFURLResponseSerialization.m │ │ ├── AFURLSessionManager.h │ │ └── AFURLSessionManager.m │ ├── LICENSE │ └── README.md │ ├── Manifest.lock │ ├── Pods.xcodeproj │ └── project.pbxproj │ └── Target Support Files │ ├── AFNetworking │ ├── AFNetworking-Info.plist │ ├── AFNetworking-dummy.m │ ├── AFNetworking-prefix.pch │ ├── AFNetworking-umbrella.h │ ├── AFNetworking.modulemap │ └── AFNetworking.xcconfig │ └── Pods-LCWebImage │ ├── Pods-LCWebImage-Info.plist │ ├── Pods-LCWebImage-acknowledgements.markdown │ ├── Pods-LCWebImage-acknowledgements.plist │ ├── Pods-LCWebImage-dummy.m │ ├── Pods-LCWebImage-frameworks-Debug-input-files.xcfilelist │ ├── Pods-LCWebImage-frameworks-Debug-output-files.xcfilelist │ ├── Pods-LCWebImage-frameworks-Release-input-files.xcfilelist │ ├── Pods-LCWebImage-frameworks-Release-output-files.xcfilelist │ ├── Pods-LCWebImage-frameworks.sh │ ├── Pods-LCWebImage-umbrella.h │ ├── Pods-LCWebImage.debug.xcconfig │ ├── Pods-LCWebImage.modulemap │ └── Pods-LCWebImage.release.xcconfig ├── LCWebImage.podspec ├── LCWebImage ├── LCAutoPurgingImageCache.h ├── LCAutoPurgingImageCache.m ├── LCWebImageManager.h ├── LCWebImageManager.m ├── UIButton+LCWebImage.h ├── UIButton+LCWebImage.m ├── UIImage+LCDecoder.h ├── UIImage+LCDecoder.m ├── UIImageView+LCWebImage.h └── UIImageView+LCWebImage.m ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | # CocoaPods 34 | # 35 | # We recommend against adding the Pods directory to your .gitignore. However 36 | # you should judge for yourself, the pros and cons are mentioned at: 37 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 38 | # 39 | # Pods/ 40 | # 41 | # Add this line if you want to avoid checking in source code from the Xcode workspace 42 | # *.xcworkspace 43 | 44 | # Carthage 45 | # 46 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 47 | # Carthage/Checkouts 48 | 49 | Carthage/Build/ 50 | 51 | # fastlane 52 | # 53 | # It is recommended to not store the screenshots in the git repo. 54 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 55 | # For more information about the recommended setup visit: 56 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 57 | 58 | fastlane/report.xml 59 | fastlane/Preview.html 60 | fastlane/screenshots/**/*.png 61 | fastlane/test_output 62 | 63 | # Code Injection 64 | # 65 | # After new code Injection tools there's a generated folder /iOSInjectionProject 66 | # https://github.com/johnno1962/injectionforxcode 67 | 68 | iOSInjectionProject/ 69 | -------------------------------------------------------------------------------- /Demo/LCWebImage.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Demo/LCWebImage.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Demo/LCWebImage.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Demo/LCWebImage.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Demo/LCWebImage/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import 9 | 10 | @interface AppDelegate : UIResponder 11 | 12 | 13 | @end 14 | 15 | -------------------------------------------------------------------------------- /Demo/LCWebImage/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import "AppDelegate.h" 9 | 10 | @interface AppDelegate () 11 | 12 | @end 13 | 14 | @implementation AppDelegate 15 | 16 | 17 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 18 | // Override point for customization after application launch. 19 | return YES; 20 | } 21 | 22 | 23 | #pragma mark - UISceneSession lifecycle 24 | 25 | 26 | - (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options { 27 | // Called when a new scene session is being created. 28 | // Use this method to select a configuration to create the new scene with. 29 | return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role]; 30 | } 31 | 32 | 33 | - (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet *)sceneSessions { 34 | // Called when the user discards a scene session. 35 | // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. 36 | // Use this method to release any resources that were specific to the discarded scenes, as they will not return. 37 | } 38 | 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Assets.xcassets/AccentColor.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "colors" : [ 3 | { 4 | "idiom" : "universal" 5 | } 6 | ], 7 | "info" : { 8 | "author" : "xcode", 9 | "version" : 1 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "scale" : "1x", 46 | "size" : "20x20" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "scale" : "2x", 51 | "size" : "20x20" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "scale" : "1x", 56 | "size" : "29x29" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "scale" : "2x", 61 | "size" : "29x29" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "scale" : "1x", 66 | "size" : "40x40" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "scale" : "2x", 71 | "size" : "40x40" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "scale" : "1x", 76 | "size" : "76x76" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "scale" : "2x", 81 | "size" : "76x76" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "scale" : "2x", 86 | "size" : "83.5x83.5" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "scale" : "1x", 91 | "size" : "1024x1024" 92 | } 93 | ], 94 | "info" : { 95 | "author" : "xcode", 96 | "version" : 1 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | $(PRODUCT_BUNDLE_PACKAGE_TYPE) 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | UIApplicationSceneManifest 24 | 25 | UIApplicationSupportsMultipleScenes 26 | 27 | UISceneConfigurations 28 | 29 | UIWindowSceneSessionRoleApplication 30 | 31 | 32 | UISceneConfigurationName 33 | Default Configuration 34 | UISceneDelegateClassName 35 | SceneDelegate 36 | UISceneStoryboardFile 37 | Main 38 | 39 | 40 | 41 | 42 | UIApplicationSupportsIndirectInputEvents 43 | 44 | UILaunchStoryboardName 45 | LaunchScreen 46 | UIMainStoryboardFile 47 | Main 48 | UIRequiredDeviceCapabilities 49 | 50 | armv7 51 | 52 | UISupportedInterfaceOrientations 53 | 54 | UIInterfaceOrientationPortrait 55 | UIInterfaceOrientationLandscapeLeft 56 | UIInterfaceOrientationLandscapeRight 57 | 58 | UISupportedInterfaceOrientations~ipad 59 | 60 | UIInterfaceOrientationPortrait 61 | UIInterfaceOrientationPortraitUpsideDown 62 | UIInterfaceOrientationLandscapeLeft 63 | UIInterfaceOrientationLandscapeRight 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Demo/LCWebImage/SceneDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // SceneDelegate.h 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import 9 | 10 | @interface SceneDelegate : UIResponder 11 | 12 | @property (strong, nonatomic) UIWindow * window; 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /Demo/LCWebImage/SceneDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // SceneDelegate.m 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import "SceneDelegate.h" 9 | 10 | @interface SceneDelegate () 11 | 12 | @end 13 | 14 | @implementation SceneDelegate 15 | 16 | 17 | - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { 18 | // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. 19 | // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. 20 | // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). 21 | } 22 | 23 | 24 | - (void)sceneDidDisconnect:(UIScene *)scene { 25 | // Called as the scene is being released by the system. 26 | // This occurs shortly after the scene enters the background, or when its session is discarded. 27 | // Release any resources associated with this scene that can be re-created the next time the scene connects. 28 | // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). 29 | } 30 | 31 | 32 | - (void)sceneDidBecomeActive:(UIScene *)scene { 33 | // Called when the scene has moved from an inactive state to an active state. 34 | // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. 35 | } 36 | 37 | 38 | - (void)sceneWillResignActive:(UIScene *)scene { 39 | // Called when the scene will move from an active state to an inactive state. 40 | // This may occur due to temporary interruptions (ex. an incoming phone call). 41 | } 42 | 43 | 44 | - (void)sceneWillEnterForeground:(UIScene *)scene { 45 | // Called as the scene transitions from the background to the foreground. 46 | // Use this method to undo the changes made on entering the background. 47 | } 48 | 49 | 50 | - (void)sceneDidEnterBackground:(UIScene *)scene { 51 | // Called as the scene transitions from the foreground to the background. 52 | // Use this method to save data, release shared resources, and store enough scene-specific state information 53 | // to restore the scene back to its current state. 54 | } 55 | 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/Headers/config.h: -------------------------------------------------------------------------------- 1 | /* src/webp/config.h. Generated from config.h.in by configure. */ 2 | /* src/webp/config.h.in. Generated from configure.ac by autoheader. */ 3 | 4 | /* Define if building universal (internal helper macro) */ 5 | /* #undef AC_APPLE_UNIVERSAL_BUILD */ 6 | 7 | /* Set to 1 if __builtin_bswap16 is available */ 8 | #define HAVE_BUILTIN_BSWAP16 1 9 | 10 | /* Set to 1 if __builtin_bswap32 is available */ 11 | #define HAVE_BUILTIN_BSWAP32 1 12 | 13 | /* Set to 1 if __builtin_bswap64 is available */ 14 | #define HAVE_BUILTIN_BSWAP64 1 15 | 16 | /* Define to 1 if you have the header file. */ 17 | #define HAVE_DLFCN_H 1 18 | 19 | /* Define to 1 if you have the header file. */ 20 | /* #undef HAVE_GLUT_GLUT_H */ 21 | 22 | /* Define to 1 if you have the header file. */ 23 | /* #undef HAVE_GL_GLUT_H */ 24 | 25 | /* Define to 1 if you have the header file. */ 26 | #define HAVE_INTTYPES_H 1 27 | 28 | /* Define to 1 if you have the header file. */ 29 | #define HAVE_MEMORY_H 1 30 | 31 | /* Define to 1 if you have the header file. */ 32 | /* #undef HAVE_OPENGL_GLUT_H */ 33 | 34 | /* Have PTHREAD_PRIO_INHERIT. */ 35 | #define HAVE_PTHREAD_PRIO_INHERIT 1 36 | 37 | /* Define to 1 if you have the header file. */ 38 | /* #undef HAVE_SHLWAPI_H */ 39 | 40 | /* Define to 1 if you have the header file. */ 41 | #define HAVE_STDINT_H 1 42 | 43 | /* Define to 1 if you have the header file. */ 44 | #define HAVE_STDLIB_H 1 45 | 46 | /* Define to 1 if you have the header file. */ 47 | #define HAVE_STRINGS_H 1 48 | 49 | /* Define to 1 if you have the header file. */ 50 | #define HAVE_STRING_H 1 51 | 52 | /* Define to 1 if you have the header file. */ 53 | #define HAVE_SYS_STAT_H 1 54 | 55 | /* Define to 1 if you have the header file. */ 56 | #define HAVE_SYS_TYPES_H 1 57 | 58 | /* Define to 1 if you have the header file. */ 59 | #define HAVE_UNISTD_H 1 60 | 61 | /* Define to 1 if you have the header file. */ 62 | /* #undef HAVE_WINCODEC_H */ 63 | 64 | /* Define to 1 if you have the header file. */ 65 | /* #undef HAVE_WINDOWS_H */ 66 | 67 | /* Define to the sub-directory in which libtool stores uninstalled libraries. 68 | */ 69 | #define LT_OBJDIR ".libs/" 70 | 71 | /* Name of package */ 72 | #define PACKAGE "libwebp" 73 | 74 | /* Define to the address where bug reports for this package should be sent. */ 75 | #define PACKAGE_BUGREPORT "https://bugs.chromium.org/p/webp" 76 | 77 | /* Define to the full name of this package. */ 78 | #define PACKAGE_NAME "libwebp" 79 | 80 | /* Define to the full name and version of this package. */ 81 | #define PACKAGE_STRING "libwebp 0.5.0" 82 | 83 | /* Define to the one symbol short name of this package. */ 84 | #define PACKAGE_TARNAME "libwebp" 85 | 86 | /* Define to the home page for this package. */ 87 | #define PACKAGE_URL "http://developers.google.com/speed/webp" 88 | 89 | /* Define to the version of this package. */ 90 | #define PACKAGE_VERSION "0.5.0" 91 | 92 | /* Define to necessary symbol if this constant uses a non-standard name on 93 | your system. */ 94 | /* #undef PTHREAD_CREATE_JOINABLE */ 95 | 96 | /* Define to 1 if you have the ANSI C header files. */ 97 | #define STDC_HEADERS 1 98 | 99 | /* Version number of package */ 100 | #define VERSION "0.5.0" 101 | 102 | /* Enable experimental code */ 103 | /* #undef WEBP_EXPERIMENTAL_FEATURES */ 104 | 105 | /* Define to 1 to force aligned memory operations */ 106 | /* #undef WEBP_FORCE_ALIGNED */ 107 | 108 | /* Set to 1 if AVX2 is supported */ 109 | /* #undef WEBP_HAVE_AVX2 */ 110 | 111 | /* Set to 1 if GIF library is installed */ 112 | /* #undef WEBP_HAVE_GIF */ 113 | 114 | /* Set to 1 if OpenGL is supported */ 115 | /* #undef WEBP_HAVE_GL */ 116 | 117 | /* Set to 1 if JPEG library is installed */ 118 | /* #undef WEBP_HAVE_JPEG */ 119 | 120 | /* Set to 1 if PNG library is installed */ 121 | /* #undef WEBP_HAVE_PNG */ 122 | 123 | /* Set to 1 if SSE2 is supported */ 124 | /* #undef WEBP_HAVE_SSE2 */ 125 | 126 | /* Set to 1 if SSE4.1 is supported */ 127 | /* #undef WEBP_HAVE_SSE41 */ 128 | 129 | /* Set to 1 if TIFF library is installed */ 130 | /* #undef WEBP_HAVE_TIFF */ 131 | 132 | /* Undefine this to disable thread support. */ 133 | #define WEBP_USE_THREAD 1 134 | 135 | /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most 136 | significant byte first (like Motorola and SPARC, unlike Intel). */ 137 | #if defined AC_APPLE_UNIVERSAL_BUILD 138 | # if defined __BIG_ENDIAN__ 139 | # define WORDS_BIGENDIAN 1 140 | # endif 141 | #else 142 | # ifndef WORDS_BIGENDIAN 143 | /* # undef WORDS_BIGENDIAN */ 144 | # endif 145 | #endif 146 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/Headers/extras.h: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the COPYING file in the root of the source 5 | // tree. An additional intellectual property rights grant can be found 6 | // in the file PATENTS. All contributing project authors may 7 | // be found in the AUTHORS file in the root of the source tree. 8 | // ----------------------------------------------------------------------------- 9 | // 10 | 11 | #ifndef WEBP_WEBP_EXTRAS_H_ 12 | #define WEBP_WEBP_EXTRAS_H_ 13 | 14 | #include "./types.h" 15 | 16 | #ifdef __cplusplus 17 | extern "C" { 18 | #endif 19 | 20 | #include "./encode.h" 21 | 22 | #define WEBP_EXTRAS_ABI_VERSION 0x0000 // MAJOR(8b) + MINOR(8b) 23 | 24 | //------------------------------------------------------------------------------ 25 | 26 | // Returns the version number of the extras library, packed in hexadecimal using 27 | // 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507. 28 | WEBP_EXTERN(int) WebPGetExtrasVersion(void); 29 | 30 | //------------------------------------------------------------------------------ 31 | // Ad-hoc colorspace importers. 32 | 33 | // Import luma sample (gray scale image) into 'picture'. The 'picture' 34 | // width and height must be set prior to calling this function. 35 | WEBP_EXTERN(int) WebPImportGray(const uint8_t* gray, WebPPicture* picture); 36 | 37 | // Import rgb sample in RGB565 packed format into 'picture'. The 'picture' 38 | // width and height must be set prior to calling this function. 39 | WEBP_EXTERN(int) WebPImportRGB565(const uint8_t* rgb565, WebPPicture* pic); 40 | 41 | // Import rgb sample in RGB4444 packed format into 'picture'. The 'picture' 42 | // width and height must be set prior to calling this function. 43 | WEBP_EXTERN(int) WebPImportRGB4444(const uint8_t* rgb4444, WebPPicture* pic); 44 | 45 | //------------------------------------------------------------------------------ 46 | 47 | #ifdef __cplusplus 48 | } // extern "C" 49 | #endif 50 | 51 | #endif /* WEBP_WEBP_EXTRAS_H_ */ 52 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/Headers/format_constants.h: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google Inc. All Rights Reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the COPYING file in the root of the source 5 | // tree. An additional intellectual property rights grant can be found 6 | // in the file PATENTS. All contributing project authors may 7 | // be found in the AUTHORS file in the root of the source tree. 8 | // ----------------------------------------------------------------------------- 9 | // 10 | // Internal header for constants related to WebP file format. 11 | // 12 | // Author: Urvang (urvang@google.com) 13 | 14 | #ifndef WEBP_WEBP_FORMAT_CONSTANTS_H_ 15 | #define WEBP_WEBP_FORMAT_CONSTANTS_H_ 16 | 17 | // Create fourcc of the chunk from the chunk tag characters. 18 | #define MKFOURCC(a, b, c, d) ((a) | (b) << 8 | (c) << 16 | (uint32_t)(d) << 24) 19 | 20 | // VP8 related constants. 21 | #define VP8_SIGNATURE 0x9d012a // Signature in VP8 data. 22 | #define VP8_MAX_PARTITION0_SIZE (1 << 19) // max size of mode partition 23 | #define VP8_MAX_PARTITION_SIZE (1 << 24) // max size for token partition 24 | #define VP8_FRAME_HEADER_SIZE 10 // Size of the frame header within VP8 data. 25 | 26 | // VP8L related constants. 27 | #define VP8L_SIGNATURE_SIZE 1 // VP8L signature size. 28 | #define VP8L_MAGIC_BYTE 0x2f // VP8L signature byte. 29 | #define VP8L_IMAGE_SIZE_BITS 14 // Number of bits used to store 30 | // width and height. 31 | #define VP8L_VERSION_BITS 3 // 3 bits reserved for version. 32 | #define VP8L_VERSION 0 // version 0 33 | #define VP8L_FRAME_HEADER_SIZE 5 // Size of the VP8L frame header. 34 | 35 | #define MAX_PALETTE_SIZE 256 36 | #define MAX_CACHE_BITS 11 37 | #define HUFFMAN_CODES_PER_META_CODE 5 38 | #define ARGB_BLACK 0xff000000 39 | 40 | #define DEFAULT_CODE_LENGTH 8 41 | #define MAX_ALLOWED_CODE_LENGTH 15 42 | 43 | #define NUM_LITERAL_CODES 256 44 | #define NUM_LENGTH_CODES 24 45 | #define NUM_DISTANCE_CODES 40 46 | #define CODE_LENGTH_CODES 19 47 | 48 | #define MIN_HUFFMAN_BITS 2 // min number of Huffman bits 49 | #define MAX_HUFFMAN_BITS 9 // max number of Huffman bits 50 | 51 | #define TRANSFORM_PRESENT 1 // The bit to be written when next data 52 | // to be read is a transform. 53 | #define NUM_TRANSFORMS 4 // Maximum number of allowed transform 54 | // in a bitstream. 55 | typedef enum { 56 | PREDICTOR_TRANSFORM = 0, 57 | CROSS_COLOR_TRANSFORM = 1, 58 | SUBTRACT_GREEN = 2, 59 | COLOR_INDEXING_TRANSFORM = 3 60 | } VP8LImageTransformType; 61 | 62 | // Alpha related constants. 63 | #define ALPHA_HEADER_LEN 1 64 | #define ALPHA_NO_COMPRESSION 0 65 | #define ALPHA_LOSSLESS_COMPRESSION 1 66 | #define ALPHA_PREPROCESSED_LEVELS 1 67 | 68 | // Mux related constants. 69 | #define TAG_SIZE 4 // Size of a chunk tag (e.g. "VP8L"). 70 | #define CHUNK_SIZE_BYTES 4 // Size needed to store chunk's size. 71 | #define CHUNK_HEADER_SIZE 8 // Size of a chunk header. 72 | #define RIFF_HEADER_SIZE 12 // Size of the RIFF header ("RIFFnnnnWEBP"). 73 | #define ANMF_CHUNK_SIZE 16 // Size of an ANMF chunk. 74 | #define ANIM_CHUNK_SIZE 6 // Size of an ANIM chunk. 75 | #define FRGM_CHUNK_SIZE 6 // Size of a FRGM chunk. 76 | #define VP8X_CHUNK_SIZE 10 // Size of a VP8X chunk. 77 | 78 | #define MAX_CANVAS_SIZE (1 << 24) // 24-bit max for VP8X width/height. 79 | #define MAX_IMAGE_AREA (1ULL << 32) // 32-bit max for width x height. 80 | #define MAX_LOOP_COUNT (1 << 16) // maximum value for loop-count 81 | #define MAX_DURATION (1 << 24) // maximum duration 82 | #define MAX_POSITION_OFFSET (1 << 24) // maximum frame/fragment x/y offset 83 | 84 | // Maximum chunk payload is such that adding the header and padding won't 85 | // overflow a uint32_t. 86 | #define MAX_CHUNK_PAYLOAD (~0U - CHUNK_HEADER_SIZE - 1) 87 | 88 | #endif /* WEBP_WEBP_FORMAT_CONSTANTS_H_ */ 89 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/Headers/mux_types.h: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google Inc. All Rights Reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the COPYING file in the root of the source 5 | // tree. An additional intellectual property rights grant can be found 6 | // in the file PATENTS. All contributing project authors may 7 | // be found in the AUTHORS file in the root of the source tree. 8 | // ----------------------------------------------------------------------------- 9 | // 10 | // Data-types common to the mux and demux libraries. 11 | // 12 | // Author: Urvang (urvang@google.com) 13 | 14 | #ifndef WEBP_WEBP_MUX_TYPES_H_ 15 | #define WEBP_WEBP_MUX_TYPES_H_ 16 | 17 | #include // free() 18 | #include // memset() 19 | #include "./types.h" 20 | 21 | #ifdef __cplusplus 22 | extern "C" { 23 | #endif 24 | 25 | // Note: forward declaring enumerations is not allowed in (strict) C and C++, 26 | // the types are left here for reference. 27 | // typedef enum WebPFeatureFlags WebPFeatureFlags; 28 | // typedef enum WebPMuxAnimDispose WebPMuxAnimDispose; 29 | // typedef enum WebPMuxAnimBlend WebPMuxAnimBlend; 30 | typedef struct WebPData WebPData; 31 | 32 | // VP8X Feature Flags. 33 | typedef enum WebPFeatureFlags { 34 | FRAGMENTS_FLAG = 0x00000001, 35 | ANIMATION_FLAG = 0x00000002, 36 | XMP_FLAG = 0x00000004, 37 | EXIF_FLAG = 0x00000008, 38 | ALPHA_FLAG = 0x00000010, 39 | ICCP_FLAG = 0x00000020 40 | } WebPFeatureFlags; 41 | 42 | // Dispose method (animation only). Indicates how the area used by the current 43 | // frame is to be treated before rendering the next frame on the canvas. 44 | typedef enum WebPMuxAnimDispose { 45 | WEBP_MUX_DISPOSE_NONE, // Do not dispose. 46 | WEBP_MUX_DISPOSE_BACKGROUND // Dispose to background color. 47 | } WebPMuxAnimDispose; 48 | 49 | // Blend operation (animation only). Indicates how transparent pixels of the 50 | // current frame are blended with those of the previous canvas. 51 | typedef enum WebPMuxAnimBlend { 52 | WEBP_MUX_BLEND, // Blend. 53 | WEBP_MUX_NO_BLEND // Do not blend. 54 | } WebPMuxAnimBlend; 55 | 56 | // Data type used to describe 'raw' data, e.g., chunk data 57 | // (ICC profile, metadata) and WebP compressed image data. 58 | struct WebPData { 59 | const uint8_t* bytes; 60 | size_t size; 61 | }; 62 | 63 | // Initializes the contents of the 'webp_data' object with default values. 64 | static WEBP_INLINE void WebPDataInit(WebPData* webp_data) { 65 | if (webp_data != NULL) { 66 | memset(webp_data, 0, sizeof(*webp_data)); 67 | } 68 | } 69 | 70 | // Clears the contents of the 'webp_data' object by calling free(). Does not 71 | // deallocate the object itself. 72 | static WEBP_INLINE void WebPDataClear(WebPData* webp_data) { 73 | if (webp_data != NULL) { 74 | free((void*)webp_data->bytes); 75 | WebPDataInit(webp_data); 76 | } 77 | } 78 | 79 | // Allocates necessary storage for 'dst' and copies the contents of 'src'. 80 | // Returns true on success. 81 | static WEBP_INLINE int WebPDataCopy(const WebPData* src, WebPData* dst) { 82 | if (src == NULL || dst == NULL) return 0; 83 | WebPDataInit(dst); 84 | if (src->bytes != NULL && src->size != 0) { 85 | dst->bytes = (uint8_t*)malloc(src->size); 86 | if (dst->bytes == NULL) return 0; 87 | memcpy((void*)dst->bytes, src->bytes, src->size); 88 | dst->size = src->size; 89 | } 90 | return 1; 91 | } 92 | 93 | #ifdef __cplusplus 94 | } // extern "C" 95 | #endif 96 | 97 | #endif /* WEBP_WEBP_MUX_TYPES_H_ */ 98 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/Headers/types.h: -------------------------------------------------------------------------------- 1 | // Copyright 2010 Google Inc. All Rights Reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the COPYING file in the root of the source 5 | // tree. An additional intellectual property rights grant can be found 6 | // in the file PATENTS. All contributing project authors may 7 | // be found in the AUTHORS file in the root of the source tree. 8 | // ----------------------------------------------------------------------------- 9 | // 10 | // Common types 11 | // 12 | // Author: Skal (pascal.massimino@gmail.com) 13 | 14 | #ifndef WEBP_WEBP_TYPES_H_ 15 | #define WEBP_WEBP_TYPES_H_ 16 | 17 | #include // for size_t 18 | 19 | #ifndef _MSC_VER 20 | #include 21 | #if defined(__cplusplus) || !defined(__STRICT_ANSI__) || \ 22 | (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) 23 | #define WEBP_INLINE inline 24 | #else 25 | #define WEBP_INLINE 26 | #endif 27 | #else 28 | typedef signed char int8_t; 29 | typedef unsigned char uint8_t; 30 | typedef signed short int16_t; 31 | typedef unsigned short uint16_t; 32 | typedef signed int int32_t; 33 | typedef unsigned int uint32_t; 34 | typedef unsigned long long int uint64_t; 35 | typedef long long int int64_t; 36 | #define WEBP_INLINE __forceinline 37 | #endif /* _MSC_VER */ 38 | 39 | #ifndef WEBP_EXTERN 40 | // This explicitly marks library functions and allows for changing the 41 | // signature for e.g., Windows DLL builds. 42 | # if defined(__GNUC__) && __GNUC__ >= 4 43 | # define WEBP_EXTERN(type) extern __attribute__ ((visibility ("default"))) type 44 | # else 45 | # define WEBP_EXTERN(type) extern type 46 | # endif /* __GNUC__ >= 4 */ 47 | #endif /* WEBP_EXTERN */ 48 | 49 | // Macro to check ABI compatibility (same major revision number) 50 | #define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8)) 51 | 52 | #endif /* WEBP_WEBP_TYPES_H_ */ 53 | -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.framework/WebP: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iLiuChang/LCWebImage/76814bba450a7471b0aeb40057ce2bfabccc1aec/Demo/LCWebImage/Vendor/WebP.framework/WebP -------------------------------------------------------------------------------- /Demo/LCWebImage/Vendor/WebP.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This script generates 'WebP.framework' (static library). 4 | # An iOS app can decode WebP images by including 'WebP.framework'. 5 | # 6 | # 1. Download the latest libwebp source code from 7 | # http://downloads.webmproject.org/releases/webp/index.html 8 | # 2. Use this script instead of the original 'iosbuild.sh' to build the WebP.framework. 9 | # It will build all modules, include mux, demux, coder and decoder. 10 | # 11 | # Notice: You should use Xcode 7 (or above) to support bitcode. 12 | 13 | set -e 14 | 15 | # Extract the latest SDK version from the final field of the form: iphoneosX.Y 16 | readonly SDK=$(xcodebuild -showsdks \ 17 | | grep iphoneos | sort | tail -n 1 | awk '{print substr($NF, 9)}' 18 | ) 19 | # Extract Xcode version. 20 | readonly XCODE=$(xcodebuild -version | grep Xcode | cut -d " " -f2) 21 | if [[ -z "${XCODE}" ]]; then 22 | echo "Xcode not available" 23 | exit 1 24 | fi 25 | 26 | readonly OLDPATH=${PATH} 27 | 28 | # Add iPhoneOS-V6 to the list of platforms below if you need armv6 support. 29 | # Note that iPhoneOS-V6 support is not available with the iOS6 SDK. 30 | PLATFORMS="iPhoneSimulator iPhoneSimulator64" 31 | PLATFORMS+=" iPhoneOS-V7 iPhoneOS-V7s iPhoneOS-V7-arm64" 32 | readonly PLATFORMS 33 | readonly SRCDIR=$(dirname $0) 34 | readonly TOPDIR=$(pwd) 35 | readonly BUILDDIR="${TOPDIR}/iosbuild" 36 | readonly TARGETDIR="${TOPDIR}/WebP.framework" 37 | readonly DEVELOPER=$(xcode-select --print-path) 38 | readonly PLATFORMSROOT="${DEVELOPER}/Platforms" 39 | readonly LIPO=$(xcrun -sdk iphoneos${SDK} -find lipo) 40 | LIBLIST='' 41 | 42 | if [[ -z "${SDK}" ]]; then 43 | echo "iOS SDK not available" 44 | exit 1 45 | elif [[ ${SDK} < 6.0 ]]; then 46 | echo "You need iOS SDK version 6.0 or above" 47 | exit 1 48 | else 49 | echo "iOS SDK Version ${SDK}" 50 | fi 51 | 52 | rm -rf ${BUILDDIR} 53 | rm -rf ${TARGETDIR} 54 | mkdir -p ${BUILDDIR} 55 | mkdir -p ${TARGETDIR}/Headers/ 56 | 57 | if [[ ! -e ${SRCDIR}/configure ]]; then 58 | if ! (cd ${SRCDIR} && sh autogen.sh); then 59 | cat < 9 | 10 | @interface ViewController : UIViewController 11 | 12 | 13 | @end 14 | 15 | -------------------------------------------------------------------------------- /Demo/LCWebImage/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import "ViewController.h" 9 | #import "UIImageView+LCWebImage.h" 10 | #import "YYImage/YYAnimatedImageView.h" 11 | #import "YYImage/YYImage.h" 12 | #import "UIButton+LCWebImage.h" 13 | @interface UIImageTableViewCell : UITableViewCell 14 | @property (nonatomic, weak) UIImageView *bgImageView; 15 | @end 16 | 17 | @implementation UIImageTableViewCell 18 | - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 19 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 20 | // UIImageView *bgImageView = [[UIImageView alloc] init]; 21 | YYAnimatedImageView *bgImageView = [[YYAnimatedImageView alloc] init]; 22 | bgImageView.contentMode = UIViewContentModeScaleAspectFill; 23 | bgImageView.layer.masksToBounds = YES; 24 | [self.contentView addSubview:bgImageView]; 25 | _bgImageView = bgImageView; 26 | return self; 27 | } 28 | - (void)layoutSubviews { 29 | [super layoutSubviews]; 30 | self.bgImageView.frame = CGRectMake(10, 10, self.frame.size.width-20, self.frame.size.height-20); 31 | } 32 | 33 | @end 34 | @interface ViewController() 35 | @property (nonatomic, strong) NSArray *images; 36 | @end 37 | 38 | @implementation ViewController 39 | 40 | - (void)viewDidLoad { 41 | [super viewDidLoad]; 42 | // 自定义解码 43 | [(LCAutoPurgingImageCache *)[LCWebImageManager defaultInstance].imageCache setCustomDecodedImage:^UIImage * _Nonnull(NSData * _Nonnull data, NSString * _Nonnull identifier) { 44 | return [[YYImage alloc] initWithData:data scale:UIScreen.mainScreen.scale]; 45 | }]; 46 | 47 | self.images = @[ 48 | // gif 49 | @"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp3.itc.cn%2Fq_70%2Fimages02%2F20210528%2Fc08685d26c254a53a8b02ed0017b7cd0.gif&refer=http%3A%2F%2Fp3.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655369709&t=6d51e3afd59f60c42a5680e2152ff47b", 50 | @"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fq_mini%2Cc_zoom%2Cw_640%2Fupload%2F20170812%2Fe8f26826df854b0baa95fbcaf7ddfeb1.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655518221&t=6a9fd3f6861986cd8bb2488fc89309e5", 51 | @"https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20191205%2Fd2dd1a08ce574cd3b1ca109f61f9844d.gif&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655518221&t=563b5020a58a4c08395de188af5ec35d", 52 | @"https://img0.baidu.com/it/u=512340543,3139277133&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281", 53 | @"https://img0.baidu.com/it/u=3217543765,3223180824&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=750", 54 | @"https://img0.baidu.com/it/u=1149498394,1442276907&fm=253&fmt=auto&app=120&f=JPEG?w=1000&h=500", 55 | @"https://img2.baidu.com/it/u=2147843660,3054818539&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313", 56 | @"https://img1.baidu.com/it/u=131948171,990039642&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500", 57 | @"https://img2.baidu.com/it/u=1404596068,2549809832&fm=253&fmt=auto&app=120&f=JPEG?w=1067&h=800", 58 | @"https://img2.baidu.com/it/u=3209059830,1377316442&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500", 59 | @"https://img2.baidu.com/it/u=4185738571,2433540613&fm=253&fmt=auto&app=138&f=JPEG?w=708&h=500", 60 | @"https://img1.baidu.com/it/u=3425784307,1085094197&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500", 61 | // webp 62 | @"https://isparta.github.io/compare-webp/image/gif_webp/webp/1.webp", 63 | @"https://isparta.github.io/compare-webp/image/gif_webp/webp/2.webp" 64 | ]; 65 | UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 66 | tableView.dataSource = self; 67 | tableView.rowHeight = 200; 68 | [tableView registerClass:UIImageTableViewCell.class forCellReuseIdentifier:@"cell"]; 69 | [self.view addSubview:tableView]; 70 | } 71 | 72 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 73 | UIImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; 74 | [cell.bgImageView lc_setImageWithURL:[NSURL URLWithString:self.images[indexPath.row]] placeholderImage:nil options:(0)]; 75 | return cell; 76 | } 77 | 78 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 79 | return self.images.count; 80 | } 81 | @end 82 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYAnimatedImageView.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYAnimatedImageView.h 3 | // YYImage 4 | // 5 | // Created by ibireme on 14/10/19. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | NS_ASSUME_NONNULL_BEGIN 15 | 16 | /** 17 | An image view for displaying animated image. 18 | 19 | @discussion It is a fully compatible `UIImageView` subclass. 20 | If the `image` or `highlightedImage` property adopt to the `YYAnimatedImage` protocol, 21 | then it can be used to play the multi-frame animation. The animation can also be 22 | controlled with the UIImageView methods `-startAnimating`, `-stopAnimating` and `-isAnimating`. 23 | 24 | This view request the frame data just in time. When the device has enough free memory, 25 | this view may cache some or all future frames in an inner buffer for lower CPU cost. 26 | Buffer size is dynamically adjusted based on the current state of the device memory. 27 | 28 | Sample Code: 29 | 30 | // ani@3x.gif 31 | YYImage *image = [YYImage imageNamed:@"ani"]; 32 | YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; 33 | [view addSubView:imageView]; 34 | */ 35 | @interface YYAnimatedImageView : UIImageView 36 | 37 | /** 38 | If the image has more than one frame, set this value to `YES` will automatically 39 | play/stop the animation when the view become visible/invisible. 40 | 41 | The default value is `YES`. 42 | */ 43 | @property (nonatomic) BOOL autoPlayAnimatedImage; 44 | 45 | /** 46 | Index of the currently displayed frame (index from 0). 47 | 48 | Set a new value to this property will cause to display the new frame immediately. 49 | If the new value is invalid, this method has no effect. 50 | 51 | You can add an observer to this property to observe the playing status. 52 | */ 53 | @property (nonatomic) NSUInteger currentAnimatedImageIndex; 54 | 55 | /** 56 | Whether the image view is playing animation currently. 57 | 58 | You can add an observer to this property to observe the playing status. 59 | */ 60 | @property (nonatomic, readonly) BOOL currentIsPlayingAnimation; 61 | 62 | /** 63 | The animation timer's runloop mode, default is `NSRunLoopCommonModes`. 64 | 65 | Set this property to `NSDefaultRunLoopMode` will make the animation pause during 66 | UIScrollView scrolling. 67 | */ 68 | @property (nonatomic, copy) NSString *runloopMode; 69 | 70 | /** 71 | The max size (in bytes) for inner frame buffer size, default is 0 (dynamically). 72 | 73 | When the device has enough free memory, this view will request and decode some or 74 | all future frame image into an inner buffer. If this property's value is 0, then 75 | the max buffer size will be dynamically adjusted based on the current state of 76 | the device free memory. Otherwise, the buffer size will be limited by this value. 77 | 78 | When receive memory warning or app enter background, the buffer will be released 79 | immediately, and may grow back at the right time. 80 | */ 81 | @property (nonatomic) NSUInteger maxBufferSize; 82 | 83 | @end 84 | 85 | 86 | 87 | /** 88 | The YYAnimatedImage protocol declares the required methods for animated image 89 | display with YYAnimatedImageView. 90 | 91 | Subclass a UIImage and implement this protocol, so that instances of that class 92 | can be set to YYAnimatedImageView.image or YYAnimatedImageView.highlightedImage 93 | to display animation. 94 | 95 | See `YYImage` and `YYFrameImage` for example. 96 | */ 97 | @protocol YYAnimatedImage 98 | @required 99 | /// Total animated frame count. 100 | /// It the frame count is less than 1, then the methods below will be ignored. 101 | - (NSUInteger)animatedImageFrameCount; 102 | 103 | /// Animation loop count, 0 means infinite looping. 104 | - (NSUInteger)animatedImageLoopCount; 105 | 106 | /// Bytes per frame (in memory). It may used to optimize memory buffer size. 107 | - (NSUInteger)animatedImageBytesPerFrame; 108 | 109 | /// Returns the frame image from a specified index. 110 | /// This method may be called on background thread. 111 | /// @param index Frame index (zero based). 112 | - (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index; 113 | 114 | /// Returns the frames's duration from a specified index. 115 | /// @param index Frame index (zero based). 116 | - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index; 117 | 118 | @optional 119 | /// A rectangle in image coordinates defining the subrectangle of the image that 120 | /// will be displayed. The rectangle should not outside the image's bounds. 121 | /// It may used to display sprite animation with a single image (sprite sheet). 122 | - (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index; 123 | @end 124 | 125 | NS_ASSUME_NONNULL_END 126 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYFrameImage.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYFrameImage.h 3 | // YYImage 4 | // 5 | // Created by ibireme on 14/12/9. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | #if __has_include() 15 | #import 16 | #elif __has_include() 17 | #import 18 | #else 19 | #import "YYAnimatedImageView.h" 20 | #endif 21 | 22 | NS_ASSUME_NONNULL_BEGIN 23 | 24 | /** 25 | An image to display frame-based animation. 26 | 27 | @discussion It is a fully compatible `UIImage` subclass. 28 | It only support system image format such as png and jpeg. 29 | The animation can be played by YYAnimatedImageView. 30 | 31 | Sample Code: 32 | 33 | NSArray *paths = @[@"/ani/frame1.png", @"/ani/frame2.png", @"/ani/frame3.png"]; 34 | NSArray *times = @[@0.1, @0.2, @0.1]; 35 | YYFrameImage *image = [YYFrameImage alloc] initWithImagePaths:paths frameDurations:times repeats:YES]; 36 | YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; 37 | [view addSubView:imageView]; 38 | */ 39 | @interface YYFrameImage : UIImage 40 | 41 | /** 42 | Create a frame animated image from files. 43 | 44 | @param paths An array of NSString objects, contains the full or 45 | partial path to each image file. 46 | e.g. @[@"/ani/1.png",@"/ani/2.png",@"/ani/3.png"] 47 | 48 | @param oneFrameDuration The duration (in seconds) per frame. 49 | 50 | @param loopCount The animation loop count, 0 means infinite. 51 | 52 | @return An initialized YYFrameImage object, or nil when an error occurs. 53 | */ 54 | - (nullable instancetype)initWithImagePaths:(NSArray *)paths 55 | oneFrameDuration:(NSTimeInterval)oneFrameDuration 56 | loopCount:(NSUInteger)loopCount; 57 | 58 | /** 59 | Create a frame animated image from files. 60 | 61 | @param paths An array of NSString objects, contains the full or 62 | partial path to each image file. 63 | e.g. @[@"/ani/frame1.png",@"/ani/frame2.png",@"/ani/frame3.png"] 64 | 65 | @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame. 66 | e.g. @[@0.1, @0.2, @0.3]; 67 | 68 | @param loopCount The animation loop count, 0 means infinite. 69 | 70 | @return An initialized YYFrameImage object, or nil when an error occurs. 71 | */ 72 | - (nullable instancetype)initWithImagePaths:(NSArray *)paths 73 | frameDurations:(NSArray *)frameDurations 74 | loopCount:(NSUInteger)loopCount; 75 | 76 | /** 77 | Create a frame animated image from an array of data. 78 | 79 | @param dataArray An array of NSData objects. 80 | 81 | @param oneFrameDuration The duration (in seconds) per frame. 82 | 83 | @param loopCount The animation loop count, 0 means infinite. 84 | 85 | @return An initialized YYFrameImage object, or nil when an error occurs. 86 | */ 87 | - (nullable instancetype)initWithImageDataArray:(NSArray *)dataArray 88 | oneFrameDuration:(NSTimeInterval)oneFrameDuration 89 | loopCount:(NSUInteger)loopCount; 90 | 91 | /** 92 | Create a frame animated image from an array of data. 93 | 94 | @param dataArray An array of NSData objects. 95 | 96 | @param frameDurations An array of NSNumber objects, contains the duration (in seconds) per frame. 97 | e.g. @[@0.1, @0.2, @0.3]; 98 | 99 | @param loopCount The animation loop count, 0 means infinite. 100 | 101 | @return An initialized YYFrameImage object, or nil when an error occurs. 102 | */ 103 | - (nullable instancetype)initWithImageDataArray:(NSArray *)dataArray 104 | frameDurations:(NSArray *)frameDurations 105 | loopCount:(NSUInteger)loopCount; 106 | 107 | @end 108 | 109 | NS_ASSUME_NONNULL_END 110 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYFrameImage.m: -------------------------------------------------------------------------------- 1 | // 2 | // YYFrameImage.m 3 | // YYImage 4 | // 5 | // Created by ibireme on 14/12/9. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import "YYFrameImage.h" 13 | #import "YYImageCoder.h" 14 | 15 | 16 | /** 17 | Return the path scale. 18 | 19 | e.g. 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Path Scale
"icon.png" 1
"icon@2x.png" 2
"icon@2.5x.png" 2.5
"icon@2x" 1
"icon@2x..png" 1
"icon@2x.png/" 1
29 | */ 30 | static CGFloat _NSStringPathScale(NSString *string) { 31 | if (string.length == 0 || [string hasSuffix:@"/"]) return 1; 32 | NSString *name = string.stringByDeletingPathExtension; 33 | __block CGFloat scale = 1; 34 | 35 | NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil]; 36 | [pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { 37 | if (result.range.location >= 3) { 38 | scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue; 39 | } 40 | }]; 41 | 42 | return scale; 43 | } 44 | 45 | 46 | 47 | @implementation YYFrameImage { 48 | NSUInteger _loopCount; 49 | NSUInteger _oneFrameBytes; 50 | NSArray *_imagePaths; 51 | NSArray *_imageDatas; 52 | NSArray *_frameDurations; 53 | } 54 | 55 | - (instancetype)initWithImagePaths:(NSArray *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount { 56 | NSMutableArray *durations = [NSMutableArray new]; 57 | for (int i = 0, max = (int)paths.count; i < max; i++) { 58 | [durations addObject:@(oneFrameDuration)]; 59 | } 60 | return [self initWithImagePaths:paths frameDurations:durations loopCount:loopCount]; 61 | } 62 | 63 | - (instancetype)initWithImagePaths:(NSArray *)paths frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount { 64 | if (paths.count == 0) return nil; 65 | if (paths.count != frameDurations.count) return nil; 66 | 67 | NSString *firstPath = paths[0]; 68 | NSData *firstData = [NSData dataWithContentsOfFile:firstPath]; 69 | CGFloat scale = _NSStringPathScale(firstPath); 70 | UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] yy_imageByDecoded]; 71 | self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp]; 72 | if (!self) return nil; 73 | long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage); 74 | _oneFrameBytes = (NSUInteger)frameByte; 75 | _imagePaths = paths.copy; 76 | _frameDurations = frameDurations.copy; 77 | _loopCount = loopCount; 78 | 79 | return self; 80 | } 81 | 82 | - (instancetype)initWithImageDataArray:(NSArray *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount { 83 | NSMutableArray *durations = [NSMutableArray new]; 84 | for (int i = 0, max = (int)dataArray.count; i < max; i++) { 85 | [durations addObject:@(oneFrameDuration)]; 86 | } 87 | return [self initWithImageDataArray:dataArray frameDurations:durations loopCount:loopCount]; 88 | } 89 | 90 | - (instancetype)initWithImageDataArray:(NSArray *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount { 91 | if (dataArray.count == 0) return nil; 92 | if (dataArray.count != frameDurations.count) return nil; 93 | 94 | NSData *firstData = dataArray[0]; 95 | CGFloat scale = [UIScreen mainScreen].scale; 96 | UIImage *firstCG = [[[UIImage alloc] initWithData:firstData] yy_imageByDecoded]; 97 | self = [self initWithCGImage:firstCG.CGImage scale:scale orientation:UIImageOrientationUp]; 98 | if (!self) return nil; 99 | long frameByte = CGImageGetBytesPerRow(firstCG.CGImage) * CGImageGetHeight(firstCG.CGImage); 100 | _oneFrameBytes = (NSUInteger)frameByte; 101 | _imageDatas = dataArray.copy; 102 | _frameDurations = frameDurations.copy; 103 | _loopCount = loopCount; 104 | 105 | return self; 106 | } 107 | 108 | #pragma mark - YYAnimtedImage 109 | 110 | - (NSUInteger)animatedImageFrameCount { 111 | if (_imagePaths) { 112 | return _imagePaths.count; 113 | } else if (_imageDatas) { 114 | return _imageDatas.count; 115 | } else { 116 | return 1; 117 | } 118 | } 119 | 120 | - (NSUInteger)animatedImageLoopCount { 121 | return _loopCount; 122 | } 123 | 124 | - (NSUInteger)animatedImageBytesPerFrame { 125 | return _oneFrameBytes; 126 | } 127 | 128 | - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { 129 | if (_imagePaths) { 130 | if (index >= _imagePaths.count) return nil; 131 | NSString *path = _imagePaths[index]; 132 | CGFloat scale = _NSStringPathScale(path); 133 | NSData *data = [NSData dataWithContentsOfFile:path]; 134 | return [[UIImage imageWithData:data scale:scale] yy_imageByDecoded]; 135 | } else if (_imageDatas) { 136 | if (index >= _imageDatas.count) return nil; 137 | NSData *data = _imageDatas[index]; 138 | return [[UIImage imageWithData:data scale:[UIScreen mainScreen].scale] yy_imageByDecoded]; 139 | } else { 140 | return index == 0 ? self : nil; 141 | } 142 | } 143 | 144 | - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { 145 | if (index >= _frameDurations.count) return 0; 146 | NSNumber *num = _frameDurations[index]; 147 | return [num doubleValue]; 148 | } 149 | 150 | @end 151 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYImage.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYImage.h 3 | // YYImage 4 | // 5 | // Created by ibireme on 14/10/20. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | #if __has_include() 15 | FOUNDATION_EXPORT double YYImageVersionNumber; 16 | FOUNDATION_EXPORT const unsigned char YYImageVersionString[]; 17 | #import 18 | #import 19 | #import 20 | #import 21 | #elif __has_include() 22 | #import 23 | #import 24 | #import 25 | #import 26 | #else 27 | #import "YYFrameImage.h" 28 | #import "YYSpriteSheetImage.h" 29 | #import "YYImageCoder.h" 30 | #import "YYAnimatedImageView.h" 31 | #endif 32 | 33 | NS_ASSUME_NONNULL_BEGIN 34 | 35 | 36 | /** 37 | A YYImage object is a high-level way to display animated image data. 38 | 39 | @discussion It is a fully compatible `UIImage` subclass. It extends the UIImage 40 | to support animated WebP, APNG and GIF format image data decoding. It also 41 | support NSCoding protocol to archive and unarchive multi-frame image data. 42 | 43 | If the image is created from multi-frame image data, and you want to play the 44 | animation, try replace UIImageView with `YYAnimatedImageView`. 45 | 46 | Sample Code: 47 | 48 | // animation@3x.webp 49 | YYImage *image = [YYImage imageNamed:@"animation.webp"]; 50 | YYAnimatedImageView *imageView = [YYAnimatedImageView alloc] initWithImage:image]; 51 | [view addSubView:imageView]; 52 | 53 | */ 54 | @interface YYImage : UIImage 55 | 56 | + (nullable YYImage *)imageNamed:(NSString *)name; // no cache! 57 | + (nullable YYImage *)imageWithContentsOfFile:(NSString *)path; 58 | + (nullable YYImage *)imageWithData:(NSData *)data; 59 | + (nullable YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale; 60 | 61 | /** 62 | If the image is created from data or file, then the value indicates the data type. 63 | */ 64 | @property (nonatomic, readonly) YYImageType animatedImageType; 65 | 66 | /** 67 | If the image is created from animated image data (multi-frame GIF/APNG/WebP), 68 | this property stores the original image data. 69 | */ 70 | @property (nullable, nonatomic, readonly) NSData *animatedImageData; 71 | 72 | /** 73 | The total memory usage (in bytes) if all frame images was loaded into memory. 74 | The value is 0 if the image is not created from a multi-frame image data. 75 | */ 76 | @property (nonatomic, readonly) NSUInteger animatedImageMemorySize; 77 | 78 | /** 79 | Preload all frame image to memory. 80 | 81 | @discussion Set this property to `YES` will block the calling thread to decode 82 | all animation frame image to memory, set to `NO` will release the preloaded frames. 83 | If the image is shared by lots of image views (such as emoticon), preload all 84 | frames will reduce the CPU cost. 85 | 86 | See `animatedImageMemorySize` for memory cost. 87 | */ 88 | @property (nonatomic) BOOL preloadAllAnimatedImageFrames; 89 | 90 | @end 91 | 92 | NS_ASSUME_NONNULL_END 93 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYImage.m: -------------------------------------------------------------------------------- 1 | // 2 | // YYImage.m 3 | // YYImage 4 | // 5 | // Created by ibireme on 14/10/20. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import "YYImage.h" 13 | 14 | /** 15 | An array of NSNumber objects, shows the best order for path scale search. 16 | e.g. iPhone3GS:@[@1,@2,@3] iPhone5:@[@2,@3,@1] iPhone6 Plus:@[@3,@2,@1] 17 | */ 18 | static NSArray *_NSBundlePreferredScales() { 19 | static NSArray *scales; 20 | static dispatch_once_t onceToken; 21 | dispatch_once(&onceToken, ^{ 22 | CGFloat screenScale = [UIScreen mainScreen].scale; 23 | if (screenScale <= 1) { 24 | scales = @[@1,@2,@3]; 25 | } else if (screenScale <= 2) { 26 | scales = @[@2,@3,@1]; 27 | } else { 28 | scales = @[@3,@2,@1]; 29 | } 30 | }); 31 | return scales; 32 | } 33 | 34 | /** 35 | Add scale modifier to the file name (without path extension), 36 | From @"name" to @"name@2x". 37 | 38 | e.g. 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
Before After(scale:2)
"icon" "icon@2x"
"icon " "icon @2x"
"icon.top" "icon.top@2x"
"/p/name" "/p/name@2x"
"/path/" "/path/"
47 | 48 | @param scale Resource scale. 49 | @return String by add scale modifier, or just return if it's not end with file name. 50 | */ 51 | static NSString *_NSStringByAppendingNameScale(NSString *string, CGFloat scale) { 52 | if (!string) return nil; 53 | if (fabs(scale - 1) <= __FLT_EPSILON__ || string.length == 0 || [string hasSuffix:@"/"]) return string.copy; 54 | return [string stringByAppendingFormat:@"@%@x", @(scale)]; 55 | } 56 | 57 | /** 58 | Return the path scale. 59 | 60 | e.g. 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 |
Path Scale
"icon.png" 1
"icon@2x.png" 2
"icon@2.5x.png" 2.5
"icon@2x" 1
"icon@2x..png" 1
"icon@2x.png/" 1
70 | */ 71 | static CGFloat _NSStringPathScale(NSString *string) { 72 | if (string.length == 0 || [string hasSuffix:@"/"]) return 1; 73 | NSString *name = string.stringByDeletingPathExtension; 74 | __block CGFloat scale = 1; 75 | 76 | NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil]; 77 | [pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { 78 | if (result.range.location >= 3) { 79 | scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue; 80 | } 81 | }]; 82 | 83 | return scale; 84 | } 85 | 86 | 87 | @implementation YYImage { 88 | YYImageDecoder *_decoder; 89 | NSArray *_preloadedFrames; 90 | dispatch_semaphore_t _preloadedLock; 91 | NSUInteger _bytesPerFrame; 92 | } 93 | 94 | + (YYImage *)imageNamed:(NSString *)name { 95 | if (name.length == 0) return nil; 96 | if ([name hasSuffix:@"/"]) return nil; 97 | 98 | NSString *res = name.stringByDeletingPathExtension; 99 | NSString *ext = name.pathExtension; 100 | NSString *path = nil; 101 | CGFloat scale = 1; 102 | 103 | // If no extension, guess by system supported (same as UIImage). 104 | NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp", @"apng"]; 105 | NSArray *scales = _NSBundlePreferredScales(); 106 | for (int s = 0; s < scales.count; s++) { 107 | scale = ((NSNumber *)scales[s]).floatValue; 108 | NSString *scaledName = _NSStringByAppendingNameScale(res, scale); 109 | for (NSString *e in exts) { 110 | path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e]; 111 | if (path) break; 112 | } 113 | if (path) break; 114 | } 115 | if (path.length == 0) return nil; 116 | 117 | NSData *data = [NSData dataWithContentsOfFile:path]; 118 | if (data.length == 0) return nil; 119 | 120 | return [[self alloc] initWithData:data scale:scale]; 121 | } 122 | 123 | + (YYImage *)imageWithContentsOfFile:(NSString *)path { 124 | return [[self alloc] initWithContentsOfFile:path]; 125 | } 126 | 127 | + (YYImage *)imageWithData:(NSData *)data { 128 | return [[self alloc] initWithData:data]; 129 | } 130 | 131 | + (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale { 132 | return [[self alloc] initWithData:data scale:scale]; 133 | } 134 | 135 | - (instancetype)initWithContentsOfFile:(NSString *)path { 136 | NSData *data = [NSData dataWithContentsOfFile:path]; 137 | return [self initWithData:data scale:_NSStringPathScale(path)]; 138 | } 139 | 140 | - (instancetype)initWithData:(NSData *)data { 141 | return [self initWithData:data scale:1]; 142 | } 143 | 144 | - (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale { 145 | if (data.length == 0) return nil; 146 | if (scale <= 0) scale = [UIScreen mainScreen].scale; 147 | _preloadedLock = dispatch_semaphore_create(1); 148 | @autoreleasepool { 149 | YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale]; 150 | YYImageFrame *frame = [decoder frameAtIndex:0 decodeForDisplay:YES]; 151 | UIImage *image = frame.image; 152 | if (!image) return nil; 153 | self = [self initWithCGImage:image.CGImage scale:decoder.scale orientation:image.imageOrientation]; 154 | if (!self) return nil; 155 | _animatedImageType = decoder.type; 156 | if (decoder.frameCount > 1) { 157 | _decoder = decoder; 158 | _bytesPerFrame = CGImageGetBytesPerRow(image.CGImage) * CGImageGetHeight(image.CGImage); 159 | _animatedImageMemorySize = _bytesPerFrame * decoder.frameCount; 160 | } 161 | self.yy_isDecodedForDisplay = YES; 162 | } 163 | return self; 164 | } 165 | 166 | - (NSData *)animatedImageData { 167 | return _decoder.data; 168 | } 169 | 170 | - (void)setPreloadAllAnimatedImageFrames:(BOOL)preloadAllAnimatedImageFrames { 171 | if (_preloadAllAnimatedImageFrames != preloadAllAnimatedImageFrames) { 172 | if (preloadAllAnimatedImageFrames && _decoder.frameCount > 0) { 173 | NSMutableArray *frames = [NSMutableArray new]; 174 | for (NSUInteger i = 0, max = _decoder.frameCount; i < max; i++) { 175 | UIImage *img = [self animatedImageFrameAtIndex:i]; 176 | if (img) { 177 | [frames addObject:img]; 178 | } else { 179 | [frames addObject:[NSNull null]]; 180 | } 181 | } 182 | dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); 183 | _preloadedFrames = frames; 184 | dispatch_semaphore_signal(_preloadedLock); 185 | } else { 186 | dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); 187 | _preloadedFrames = nil; 188 | dispatch_semaphore_signal(_preloadedLock); 189 | } 190 | } 191 | } 192 | 193 | #pragma mark - protocol NSCoding 194 | 195 | - (instancetype)initWithCoder:(NSCoder *)aDecoder { 196 | NSNumber *scale = [aDecoder decodeObjectForKey:@"YYImageScale"]; 197 | NSData *data = [aDecoder decodeObjectForKey:@"YYImageData"]; 198 | if (data.length) { 199 | self = [self initWithData:data scale:scale.doubleValue]; 200 | } else { 201 | self = [super initWithCoder:aDecoder]; 202 | } 203 | return self; 204 | } 205 | 206 | - (void)encodeWithCoder:(NSCoder *)aCoder { 207 | if (_decoder.data.length) { 208 | [aCoder encodeObject:@(self.scale) forKey:@"YYImageScale"]; 209 | [aCoder encodeObject:_decoder.data forKey:@"YYImageData"]; 210 | } else { 211 | [super encodeWithCoder:aCoder]; // Apple use UIImagePNGRepresentation() to encode UIImage. 212 | } 213 | } 214 | 215 | + (BOOL)supportsSecureCoding { 216 | return YES; 217 | } 218 | 219 | #pragma mark - protocol YYAnimatedImage 220 | 221 | - (NSUInteger)animatedImageFrameCount { 222 | return _decoder.frameCount; 223 | } 224 | 225 | - (NSUInteger)animatedImageLoopCount { 226 | return _decoder.loopCount; 227 | } 228 | 229 | - (NSUInteger)animatedImageBytesPerFrame { 230 | return _bytesPerFrame; 231 | } 232 | 233 | - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { 234 | if (index >= _decoder.frameCount) return nil; 235 | dispatch_semaphore_wait(_preloadedLock, DISPATCH_TIME_FOREVER); 236 | UIImage *image = _preloadedFrames[index]; 237 | dispatch_semaphore_signal(_preloadedLock); 238 | if (image) return image == (id)[NSNull null] ? nil : image; 239 | return [_decoder frameAtIndex:index decodeForDisplay:YES].image; 240 | } 241 | 242 | - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { 243 | NSTimeInterval duration = [_decoder frameDurationAtIndex:index]; 244 | 245 | /* 246 | http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp 247 | Many annoying ads specify a 0 duration to make an image flash as quickly as 248 | possible. We follow Safari and Firefox's behavior and use a duration of 100 ms 249 | for any frames that specify a duration of <= 10 ms. 250 | See and for more information. 251 | 252 | See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. 253 | */ 254 | if (duration < 0.011f) return 0.100f; 255 | return duration; 256 | } 257 | 258 | @end 259 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYSpriteSheetImage.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYSpriteImage.h 3 | // YYImage 4 | // 5 | // Created by ibireme on 15/4/21. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | #if __has_include() 15 | #import 16 | #elif __has_include() 17 | #import 18 | #else 19 | #import "YYAnimatedImageView.h" 20 | #endif 21 | 22 | NS_ASSUME_NONNULL_BEGIN 23 | 24 | /** 25 | An image to display sprite sheet animation. 26 | 27 | @discussion It is a fully compatible `UIImage` subclass. 28 | The animation can be played by YYAnimatedImageView. 29 | 30 | Sample Code: 31 | 32 | // 8 * 12 sprites in a single sheet image 33 | UIImage *spriteSheet = [UIImage imageNamed:@"sprite-sheet"]; 34 | NSMutableArray *contentRects = [NSMutableArray new]; 35 | NSMutableArray *durations = [NSMutableArray new]; 36 | for (int j = 0; j < 12; j++) { 37 | for (int i = 0; i < 8; i++) { 38 | CGRect rect; 39 | rect.size = CGSizeMake(img.size.width / 8, img.size.height / 12); 40 | rect.origin.x = img.size.width / 8 * i; 41 | rect.origin.y = img.size.height / 12 * j; 42 | [contentRects addObject:[NSValue valueWithCGRect:rect]]; 43 | [durations addObject:@(1 / 60.0)]; 44 | } 45 | } 46 | YYSpriteSheetImage *sprite; 47 | sprite = [[YYSpriteSheetImage alloc] initWithSpriteSheetImage:img 48 | contentRects:contentRects 49 | frameDurations:durations 50 | loopCount:0]; 51 | YYAnimatedImageView *imgView = [YYAnimatedImageView new]; 52 | imgView.size = CGSizeMake(img.size.width / 8, img.size.height / 12); 53 | imgView.image = sprite; 54 | 55 | 56 | 57 | @discussion It can also be used to display single frame in sprite sheet image. 58 | Sample Code: 59 | 60 | YYSpriteSheetImage *sheet = ...; 61 | UIImageView *imageView = ...; 62 | imageView.image = sheet; 63 | imageView.layer.contentsRect = [sheet contentsRectForCALayerAtIndex:6]; 64 | 65 | */ 66 | @interface YYSpriteSheetImage : UIImage 67 | 68 | /** 69 | Creates and returns an image object. 70 | 71 | @param image The sprite sheet image (contains all frames). 72 | 73 | @param contentRects The sprite sheet image frame rects in the image coordinates. 74 | The rectangle should not outside the image's bounds. The objects in this array 75 | should be created with [NSValue valueWithCGRect:]. 76 | 77 | @param frameDurations The sprite sheet image frame's durations in seconds. 78 | The objects in this array should be NSNumber. 79 | 80 | @param loopCount Animation loop count, 0 means infinite looping. 81 | 82 | @return An image object, or nil if an error occurs. 83 | */ 84 | - (nullable instancetype)initWithSpriteSheetImage:(UIImage *)image 85 | contentRects:(NSArray *)contentRects 86 | frameDurations:(NSArray *)frameDurations 87 | loopCount:(NSUInteger)loopCount; 88 | 89 | @property (nonatomic, readonly) NSArray *contentRects; 90 | @property (nonatomic, readonly) NSArray *frameDurations; 91 | @property (nonatomic, readonly) NSUInteger loopCount; 92 | 93 | /** 94 | Get the contents rect for CALayer. 95 | See "contentsRect" property in CALayer for more information. 96 | 97 | @param index Index of frame. 98 | @return Contents Rect. 99 | */ 100 | - (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index; 101 | 102 | @end 103 | 104 | NS_ASSUME_NONNULL_END 105 | -------------------------------------------------------------------------------- /Demo/LCWebImage/YYImage/YYSpriteSheetImage.m: -------------------------------------------------------------------------------- 1 | // 2 | // YYSpriteImage.m 3 | // YYImage 4 | // 5 | // Created by ibireme on 15/4/21. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import "YYSpriteSheetImage.h" 13 | 14 | @implementation YYSpriteSheetImage 15 | 16 | - (instancetype)initWithSpriteSheetImage:(UIImage *)image 17 | contentRects:(NSArray *)contentRects 18 | frameDurations:(NSArray *)frameDurations 19 | loopCount:(NSUInteger)loopCount { 20 | if (!image.CGImage) return nil; 21 | if (contentRects.count < 1 || frameDurations.count < 1) return nil; 22 | if (contentRects.count != frameDurations.count) return nil; 23 | 24 | self = [super initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; 25 | if (!self) return nil; 26 | 27 | _contentRects = contentRects.copy; 28 | _frameDurations = frameDurations.copy; 29 | _loopCount = loopCount; 30 | return self; 31 | } 32 | 33 | - (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index { 34 | CGRect layerRect = CGRectMake(0, 0, 1, 1); 35 | if (index >= _contentRects.count) return layerRect; 36 | 37 | CGSize imageSize = self.size; 38 | CGRect rect = [self animatedImageContentsRectAtIndex:index]; 39 | if (imageSize.width > 0.01 && imageSize.height > 0.01) { 40 | layerRect.origin.x = rect.origin.x / imageSize.width; 41 | layerRect.origin.y = rect.origin.y / imageSize.height; 42 | layerRect.size.width = rect.size.width / imageSize.width; 43 | layerRect.size.height = rect.size.height / imageSize.height; 44 | layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1)); 45 | if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) { 46 | layerRect = CGRectMake(0, 0, 1, 1); 47 | } 48 | } 49 | return layerRect; 50 | } 51 | 52 | #pragma mark @protocol YYAnimatedImage 53 | 54 | - (NSUInteger)animatedImageFrameCount { 55 | return _contentRects.count; 56 | } 57 | 58 | - (NSUInteger)animatedImageLoopCount { 59 | return _loopCount; 60 | } 61 | 62 | - (NSUInteger)animatedImageBytesPerFrame { 63 | return 0; 64 | } 65 | 66 | - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { 67 | return self; 68 | } 69 | 70 | - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { 71 | if (index >= _frameDurations.count) return 0; 72 | return ((NSNumber *)_frameDurations[index]).doubleValue; 73 | } 74 | 75 | - (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index { 76 | if (index >= _contentRects.count) return CGRectZero; 77 | return ((NSValue *)_contentRects[index]).CGRectValue; 78 | } 79 | 80 | @end 81 | -------------------------------------------------------------------------------- /Demo/LCWebImage/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // LCWebImage 4 | // 5 | // Created by 刘畅 on 2022/5/21. 6 | // 7 | 8 | #import 9 | #import "AppDelegate.h" 10 | 11 | int main(int argc, char * argv[]) { 12 | NSString * appDelegateClassName; 13 | @autoreleasepool { 14 | // Setup code that might create autoreleased objects goes here. 15 | appDelegateClassName = NSStringFromClass([AppDelegate class]); 16 | } 17 | return UIApplicationMain(argc, argv, nil, appDelegateClassName); 18 | } 19 | -------------------------------------------------------------------------------- /Demo/Podfile: -------------------------------------------------------------------------------- 1 | # Uncomment the next line to define a global platform for your project 2 | # platform :ios, '9.0' 3 | 4 | target 'LCWebImage' do 5 | # Comment the next line if you don't want to use dynamic frameworks 6 | use_frameworks! 7 | 8 | pod 'AFNetworking/NSURLSession' 9 | 10 | end 11 | -------------------------------------------------------------------------------- /Demo/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - AFNetworking/NSURLSession (4.0.1): 3 | - AFNetworking/Reachability 4 | - AFNetworking/Security 5 | - AFNetworking/Serialization 6 | - AFNetworking/Reachability (4.0.1) 7 | - AFNetworking/Security (4.0.1) 8 | - AFNetworking/Serialization (4.0.1) 9 | 10 | DEPENDENCIES: 11 | - AFNetworking/NSURLSession 12 | 13 | SPEC REPOS: 14 | trunk: 15 | - AFNetworking 16 | 17 | SPEC CHECKSUMS: 18 | AFNetworking: 7864c38297c79aaca1500c33288e429c3451fdce 19 | 20 | PODFILE CHECKSUM: 041567286b2264d827f24eed23468038119cf51b 21 | 22 | COCOAPODS: 1.8.4 23 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h: -------------------------------------------------------------------------------- 1 | // AFCompatibilityMacros.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #ifndef AFCompatibilityMacros_h 23 | #define AFCompatibilityMacros_h 24 | 25 | #ifdef API_AVAILABLE 26 | #define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__) 27 | #else 28 | #define AF_API_AVAILABLE(...) 29 | #endif // API_AVAILABLE 30 | 31 | #ifdef API_UNAVAILABLE 32 | #define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__) 33 | #else 34 | #define AF_API_UNAVAILABLE(...) 35 | #endif // API_UNAVAILABLE 36 | 37 | #if __has_warning("-Wunguarded-availability-new") 38 | #define AF_CAN_USE_AT_AVAILABLE 1 39 | #else 40 | #define AF_CAN_USE_AT_AVAILABLE 0 41 | #endif 42 | 43 | #if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000)) 44 | #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0 45 | #else 46 | #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1 47 | #endif 48 | 49 | #endif /* AFCompatibilityMacros_h */ 50 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if !TARGET_OS_WATCH 25 | #import 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 28 | AFNetworkReachabilityStatusUnknown = -1, 29 | AFNetworkReachabilityStatusNotReachable = 0, 30 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 31 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 32 | }; 33 | 34 | NS_ASSUME_NONNULL_BEGIN 35 | 36 | /** 37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 38 | 39 | Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. 40 | 41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) 42 | 43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 44 | */ 45 | @interface AFNetworkReachabilityManager : NSObject 46 | 47 | /** 48 | The current network reachability status. 49 | */ 50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 51 | 52 | /** 53 | Whether or not the network is currently reachable. 54 | */ 55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 56 | 57 | /** 58 | Whether or not the network is currently reachable via WWAN. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WiFi. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 66 | 67 | ///--------------------- 68 | /// @name Initialization 69 | ///--------------------- 70 | 71 | /** 72 | Returns the shared network reachability manager. 73 | */ 74 | + (instancetype)sharedManager; 75 | 76 | /** 77 | Creates and returns a network reachability manager with the default socket address. 78 | 79 | @return An initialized network reachability manager, actively monitoring the default socket address. 80 | */ 81 | + (instancetype)manager; 82 | 83 | /** 84 | Creates and returns a network reachability manager for the specified domain. 85 | 86 | @param domain The domain used to evaluate network reachability. 87 | 88 | @return An initialized network reachability manager, actively monitoring the specified domain. 89 | */ 90 | + (instancetype)managerForDomain:(NSString *)domain; 91 | 92 | /** 93 | Creates and returns a network reachability manager for the socket address. 94 | 95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. 96 | 97 | @return An initialized network reachability manager, actively monitoring the specified socket address. 98 | */ 99 | + (instancetype)managerForAddress:(const void *)address; 100 | 101 | /** 102 | Initializes an instance of a network reachability manager from the specified reachability object. 103 | 104 | @param reachability The reachability object to monitor. 105 | 106 | @return An initialized network reachability manager, actively monitoring the specified reachability. 107 | */ 108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 109 | 110 | /** 111 | * Unavailable initializer 112 | */ 113 | + (instancetype)new NS_UNAVAILABLE; 114 | 115 | /** 116 | * Unavailable initializer 117 | */ 118 | - (instancetype)init NS_UNAVAILABLE; 119 | 120 | ///-------------------------------------------------- 121 | /// @name Starting & Stopping Reachability Monitoring 122 | ///-------------------------------------------------- 123 | 124 | /** 125 | Starts monitoring for changes in network reachability status. 126 | */ 127 | - (void)startMonitoring; 128 | 129 | /** 130 | Stops monitoring for changes in network reachability status. 131 | */ 132 | - (void)stopMonitoring; 133 | 134 | ///------------------------------------------------- 135 | /// @name Getting Localized Reachability Description 136 | ///------------------------------------------------- 137 | 138 | /** 139 | Returns a localized string representation of the current network reachability status. 140 | */ 141 | - (NSString *)localizedNetworkReachabilityStatusString; 142 | 143 | ///--------------------------------------------------- 144 | /// @name Setting Network Reachability Change Callback 145 | ///--------------------------------------------------- 146 | 147 | /** 148 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 149 | 150 | @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. 151 | */ 152 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 153 | 154 | @end 155 | 156 | ///---------------- 157 | /// @name Constants 158 | ///---------------- 159 | 160 | /** 161 | ## Network Reachability 162 | 163 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 164 | 165 | enum { 166 | AFNetworkReachabilityStatusUnknown, 167 | AFNetworkReachabilityStatusNotReachable, 168 | AFNetworkReachabilityStatusReachableViaWWAN, 169 | AFNetworkReachabilityStatusReachableViaWiFi, 170 | } 171 | 172 | `AFNetworkReachabilityStatusUnknown` 173 | The `baseURL` host reachability is not known. 174 | 175 | `AFNetworkReachabilityStatusNotReachable` 176 | The `baseURL` host cannot be reached. 177 | 178 | `AFNetworkReachabilityStatusReachableViaWWAN` 179 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 180 | 181 | `AFNetworkReachabilityStatusReachableViaWiFi` 182 | The `baseURL` host can be reached via a Wi-Fi connection. 183 | 184 | ### Keys for Notification UserInfo Dictionary 185 | 186 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 187 | 188 | `AFNetworkingReachabilityNotificationStatusItem` 189 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 190 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 191 | */ 192 | 193 | ///-------------------- 194 | /// @name Notifications 195 | ///-------------------- 196 | 197 | /** 198 | Posted when network reachability changes. 199 | This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. 200 | 201 | @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). 202 | */ 203 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 204 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 205 | 206 | ///-------------------- 207 | /// @name Functions 208 | ///-------------------- 209 | 210 | /** 211 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 212 | */ 213 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 214 | 215 | NS_ASSUME_NONNULL_END 216 | #endif 217 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkReachabilityManager.h" 23 | #if !TARGET_OS_WATCH 24 | 25 | #import 26 | #import 27 | #import 28 | #import 29 | #import 30 | 31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; 32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; 33 | 34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); 35 | typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status); 36 | 37 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { 38 | switch (status) { 39 | case AFNetworkReachabilityStatusNotReachable: 40 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); 41 | case AFNetworkReachabilityStatusReachableViaWWAN: 42 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); 43 | case AFNetworkReachabilityStatusReachableViaWiFi: 44 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); 45 | case AFNetworkReachabilityStatusUnknown: 46 | default: 47 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); 48 | } 49 | } 50 | 51 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { 52 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); 53 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); 54 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); 55 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); 56 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); 57 | 58 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; 59 | if (isNetworkReachable == NO) { 60 | status = AFNetworkReachabilityStatusNotReachable; 61 | } 62 | #if TARGET_OS_IPHONE 63 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { 64 | status = AFNetworkReachabilityStatusReachableViaWWAN; 65 | } 66 | #endif 67 | else { 68 | status = AFNetworkReachabilityStatusReachableViaWiFi; 69 | } 70 | 71 | return status; 72 | } 73 | 74 | /** 75 | * Queue a status change notification for the main thread. 76 | * 77 | * This is done to ensure that the notifications are received in the same order 78 | * as they are sent. If notifications are sent directly, it is possible that 79 | * a queued notification (for an earlier status condition) is processed after 80 | * the later update, resulting in the listener being left in the wrong state. 81 | */ 82 | static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) { 83 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 84 | dispatch_async(dispatch_get_main_queue(), ^{ 85 | AFNetworkReachabilityManager *manager = nil; 86 | if (block) { 87 | manager = block(status); 88 | } 89 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 90 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 91 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo]; 92 | }); 93 | } 94 | 95 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { 96 | AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info); 97 | } 98 | 99 | 100 | static const void * AFNetworkReachabilityRetainCallback(const void *info) { 101 | return Block_copy(info); 102 | } 103 | 104 | static void AFNetworkReachabilityReleaseCallback(const void *info) { 105 | if (info) { 106 | Block_release(info); 107 | } 108 | } 109 | 110 | @interface AFNetworkReachabilityManager () 111 | @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; 112 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 113 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; 114 | @end 115 | 116 | @implementation AFNetworkReachabilityManager 117 | 118 | + (instancetype)sharedManager { 119 | static AFNetworkReachabilityManager *_sharedManager = nil; 120 | static dispatch_once_t onceToken; 121 | dispatch_once(&onceToken, ^{ 122 | _sharedManager = [self manager]; 123 | }); 124 | 125 | return _sharedManager; 126 | } 127 | 128 | + (instancetype)managerForDomain:(NSString *)domain { 129 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 130 | 131 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 132 | 133 | CFRelease(reachability); 134 | 135 | return manager; 136 | } 137 | 138 | + (instancetype)managerForAddress:(const void *)address { 139 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 140 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 141 | 142 | CFRelease(reachability); 143 | 144 | return manager; 145 | } 146 | 147 | + (instancetype)manager 148 | { 149 | #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) 150 | struct sockaddr_in6 address; 151 | bzero(&address, sizeof(address)); 152 | address.sin6_len = sizeof(address); 153 | address.sin6_family = AF_INET6; 154 | #else 155 | struct sockaddr_in address; 156 | bzero(&address, sizeof(address)); 157 | address.sin_len = sizeof(address); 158 | address.sin_family = AF_INET; 159 | #endif 160 | return [self managerForAddress:&address]; 161 | } 162 | 163 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { 164 | self = [super init]; 165 | if (!self) { 166 | return nil; 167 | } 168 | 169 | _networkReachability = CFRetain(reachability); 170 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; 171 | 172 | return self; 173 | } 174 | 175 | - (instancetype)init 176 | { 177 | @throw [NSException exceptionWithName:NSGenericException 178 | reason:@"`-init` unavailable. Use `-initWithReachability:` instead" 179 | userInfo:nil]; 180 | return nil; 181 | } 182 | 183 | - (void)dealloc { 184 | [self stopMonitoring]; 185 | 186 | if (_networkReachability != NULL) { 187 | CFRelease(_networkReachability); 188 | } 189 | } 190 | 191 | #pragma mark - 192 | 193 | - (BOOL)isReachable { 194 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 195 | } 196 | 197 | - (BOOL)isReachableViaWWAN { 198 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 199 | } 200 | 201 | - (BOOL)isReachableViaWiFi { 202 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 203 | } 204 | 205 | #pragma mark - 206 | 207 | - (void)startMonitoring { 208 | [self stopMonitoring]; 209 | 210 | if (!self.networkReachability) { 211 | return; 212 | } 213 | 214 | __weak __typeof(self)weakSelf = self; 215 | AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) { 216 | __strong __typeof(weakSelf)strongSelf = weakSelf; 217 | 218 | strongSelf.networkReachabilityStatus = status; 219 | if (strongSelf.networkReachabilityStatusBlock) { 220 | strongSelf.networkReachabilityStatusBlock(status); 221 | } 222 | 223 | return strongSelf; 224 | }; 225 | 226 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 227 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); 228 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 229 | 230 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 231 | SCNetworkReachabilityFlags flags; 232 | if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { 233 | AFPostReachabilityStatusChange(flags, callback); 234 | } 235 | }); 236 | } 237 | 238 | - (void)stopMonitoring { 239 | if (!self.networkReachability) { 240 | return; 241 | } 242 | 243 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 244 | } 245 | 246 | #pragma mark - 247 | 248 | - (NSString *)localizedNetworkReachabilityStatusString { 249 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 250 | } 251 | 252 | #pragma mark - 253 | 254 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 255 | self.networkReachabilityStatusBlock = block; 256 | } 257 | 258 | #pragma mark - NSKeyValueObserving 259 | 260 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 261 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 262 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 263 | } 264 | 265 | return [super keyPathsForValuesAffectingValueForKey:key]; 266 | } 267 | 268 | @end 269 | #endif 270 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. 48 | 49 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 50 | 51 | @see policyWithPinningMode:withPinnedCertificates: 52 | */ 53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates; 54 | 55 | /** 56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 57 | */ 58 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 59 | 60 | /** 61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 62 | */ 63 | @property (nonatomic, assign) BOOL validatesDomainName; 64 | 65 | ///----------------------------------------- 66 | /// @name Getting Certificates from the Bundle 67 | ///----------------------------------------- 68 | 69 | /** 70 | Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. 71 | 72 | @return The certificates included in the given bundle. 73 | */ 74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle; 75 | 76 | ///----------------------------------------- 77 | /// @name Getting Specific Security Policies 78 | ///----------------------------------------- 79 | 80 | /** 81 | Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. 82 | 83 | @return The default security policy. 84 | */ 85 | + (instancetype)defaultPolicy; 86 | 87 | ///--------------------- 88 | /// @name Initialization 89 | ///--------------------- 90 | 91 | /** 92 | Creates and returns a security policy with the specified pinning mode. 93 | 94 | Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead. 95 | 96 | @param pinningMode The SSL pinning mode. 97 | 98 | @return A new security policy. 99 | 100 | @see -policyWithPinningMode:withPinnedCertificates: 101 | */ 102 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 103 | 104 | /** 105 | Creates and returns a security policy with the specified pinning mode. 106 | 107 | @param pinningMode The SSL pinning mode. 108 | @param pinnedCertificates The certificates to pin against. 109 | 110 | @return A new security policy. 111 | 112 | @see +certificatesInBundle: 113 | @see -pinnedCertificates 114 | */ 115 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; 116 | 117 | ///------------------------------ 118 | /// @name Evaluating Server Trust 119 | ///------------------------------ 120 | 121 | /** 122 | Whether or not the specified server trust should be accepted, based on the security policy. 123 | 124 | This method should be used when responding to an authentication challenge from a server. 125 | 126 | @param serverTrust The X.509 certificate trust of the server. 127 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 128 | 129 | @return Whether or not to trust the server. 130 | */ 131 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 132 | forDomain:(nullable NSString *)domain; 133 | 134 | @end 135 | 136 | NS_ASSUME_NONNULL_END 137 | 138 | ///---------------- 139 | /// @name Constants 140 | ///---------------- 141 | 142 | /** 143 | ## SSL Pinning Modes 144 | 145 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 146 | 147 | enum { 148 | AFSSLPinningModeNone, 149 | AFSSLPinningModePublicKey, 150 | AFSSLPinningModeCertificate, 151 | } 152 | 153 | `AFSSLPinningModeNone` 154 | Do not used pinned certificates to validate servers. 155 | 156 | `AFSSLPinningModePublicKey` 157 | Validate host certificates against public keys of pinned certificates. 158 | 159 | `AFSSLPinningModeCertificate` 160 | Validate host certificates against pinned certificates. 161 | */ 162 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFSecurityPolicy.h" 23 | 24 | #import 25 | 26 | #if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV 27 | static NSData * AFSecKeyGetData(SecKeyRef key) { 28 | CFDataRef data = NULL; 29 | 30 | __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); 31 | 32 | return (__bridge_transfer NSData *)data; 33 | 34 | _out: 35 | if (data) { 36 | CFRelease(data); 37 | } 38 | 39 | return nil; 40 | } 41 | #endif 42 | 43 | static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { 44 | #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV 45 | return [(__bridge id)key1 isEqual:(__bridge id)key2]; 46 | #else 47 | return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; 48 | #endif 49 | } 50 | 51 | static id AFPublicKeyForCertificate(NSData *certificate) { 52 | id allowedPublicKey = nil; 53 | SecCertificateRef allowedCertificate; 54 | SecPolicyRef policy = nil; 55 | SecTrustRef allowedTrust = nil; 56 | SecTrustResultType result; 57 | 58 | allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); 59 | __Require_Quiet(allowedCertificate != NULL, _out); 60 | 61 | policy = SecPolicyCreateBasicX509(); 62 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); 63 | #pragma clang diagnostic push 64 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" 65 | __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); 66 | #pragma clang diagnostic pop 67 | 68 | allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); 69 | 70 | _out: 71 | if (allowedTrust) { 72 | CFRelease(allowedTrust); 73 | } 74 | 75 | if (policy) { 76 | CFRelease(policy); 77 | } 78 | 79 | if (allowedCertificate) { 80 | CFRelease(allowedCertificate); 81 | } 82 | 83 | return allowedPublicKey; 84 | } 85 | 86 | static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { 87 | BOOL isValid = NO; 88 | SecTrustResultType result; 89 | #pragma clang diagnostic push 90 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" 91 | __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); 92 | #pragma clang diagnostic pop 93 | 94 | isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); 95 | 96 | _out: 97 | return isValid; 98 | } 99 | 100 | static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { 101 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 102 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 103 | 104 | for (CFIndex i = 0; i < certificateCount; i++) { 105 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 106 | [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; 107 | } 108 | 109 | return [NSArray arrayWithArray:trustChain]; 110 | } 111 | 112 | static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { 113 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 114 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 115 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 116 | for (CFIndex i = 0; i < certificateCount; i++) { 117 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 118 | 119 | SecCertificateRef someCertificates[] = {certificate}; 120 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); 121 | 122 | SecTrustRef trust; 123 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); 124 | SecTrustResultType result; 125 | #pragma clang diagnostic push 126 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" 127 | __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); 128 | #pragma clang diagnostic pop 129 | [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; 130 | 131 | _out: 132 | if (trust) { 133 | CFRelease(trust); 134 | } 135 | 136 | if (certificates) { 137 | CFRelease(certificates); 138 | } 139 | 140 | continue; 141 | } 142 | CFRelease(policy); 143 | 144 | return [NSArray arrayWithArray:trustChain]; 145 | } 146 | 147 | #pragma mark - 148 | 149 | @interface AFSecurityPolicy() 150 | @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 151 | @property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; 152 | @end 153 | 154 | @implementation AFSecurityPolicy 155 | 156 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle { 157 | NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; 158 | 159 | NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; 160 | for (NSString *path in paths) { 161 | NSData *certificateData = [NSData dataWithContentsOfFile:path]; 162 | [certificates addObject:certificateData]; 163 | } 164 | 165 | return [NSSet setWithSet:certificates]; 166 | } 167 | 168 | + (instancetype)defaultPolicy { 169 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 170 | securityPolicy.SSLPinningMode = AFSSLPinningModeNone; 171 | 172 | return securityPolicy; 173 | } 174 | 175 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { 176 | NSSet *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]]; 177 | return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates]; 178 | } 179 | 180 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { 181 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 182 | securityPolicy.SSLPinningMode = pinningMode; 183 | 184 | [securityPolicy setPinnedCertificates:pinnedCertificates]; 185 | 186 | return securityPolicy; 187 | } 188 | 189 | - (instancetype)init { 190 | self = [super init]; 191 | if (!self) { 192 | return nil; 193 | } 194 | 195 | self.validatesDomainName = YES; 196 | 197 | return self; 198 | } 199 | 200 | - (void)setPinnedCertificates:(NSSet *)pinnedCertificates { 201 | _pinnedCertificates = pinnedCertificates; 202 | 203 | if (self.pinnedCertificates) { 204 | NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; 205 | for (NSData *certificate in self.pinnedCertificates) { 206 | id publicKey = AFPublicKeyForCertificate(certificate); 207 | if (!publicKey) { 208 | continue; 209 | } 210 | [mutablePinnedPublicKeys addObject:publicKey]; 211 | } 212 | self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; 213 | } else { 214 | self.pinnedPublicKeys = nil; 215 | } 216 | } 217 | 218 | #pragma mark - 219 | 220 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 221 | forDomain:(NSString *)domain 222 | { 223 | if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { 224 | // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html 225 | // According to the docs, you should only trust your provided certs for evaluation. 226 | // Pinned certificates are added to the trust. Without pinned certificates, 227 | // there is nothing to evaluate against. 228 | // 229 | // From Apple Docs: 230 | // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). 231 | // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." 232 | NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); 233 | return NO; 234 | } 235 | 236 | NSMutableArray *policies = [NSMutableArray array]; 237 | if (self.validatesDomainName) { 238 | [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; 239 | } else { 240 | [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; 241 | } 242 | 243 | SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); 244 | 245 | if (self.SSLPinningMode == AFSSLPinningModeNone) { 246 | return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); 247 | } else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) { 248 | return NO; 249 | } 250 | 251 | switch (self.SSLPinningMode) { 252 | case AFSSLPinningModeCertificate: { 253 | NSMutableArray *pinnedCertificates = [NSMutableArray array]; 254 | for (NSData *certificateData in self.pinnedCertificates) { 255 | [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; 256 | } 257 | SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); 258 | 259 | if (!AFServerTrustIsValid(serverTrust)) { 260 | return NO; 261 | } 262 | 263 | // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) 264 | NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); 265 | 266 | for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { 267 | if ([self.pinnedCertificates containsObject:trustChainCertificate]) { 268 | return YES; 269 | } 270 | } 271 | 272 | return NO; 273 | } 274 | case AFSSLPinningModePublicKey: { 275 | NSUInteger trustedPublicKeyCount = 0; 276 | NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); 277 | 278 | for (id trustChainPublicKey in publicKeys) { 279 | for (id pinnedPublicKey in self.pinnedPublicKeys) { 280 | if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { 281 | trustedPublicKeyCount += 1; 282 | } 283 | } 284 | } 285 | return trustedPublicKeyCount > 0; 286 | } 287 | 288 | default: 289 | return NO; 290 | } 291 | 292 | return NO; 293 | } 294 | 295 | #pragma mark - NSKeyValueObserving 296 | 297 | + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { 298 | return [NSSet setWithObject:@"pinnedCertificates"]; 299 | } 300 | 301 | #pragma mark - NSSecureCoding 302 | 303 | + (BOOL)supportsSecureCoding { 304 | return YES; 305 | } 306 | 307 | - (instancetype)initWithCoder:(NSCoder *)decoder { 308 | 309 | self = [self init]; 310 | if (!self) { 311 | return nil; 312 | } 313 | 314 | self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; 315 | self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 316 | self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; 317 | self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 318 | 319 | return self; 320 | } 321 | 322 | - (void)encodeWithCoder:(NSCoder *)coder { 323 | [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; 324 | [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 325 | [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; 326 | [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 327 | } 328 | 329 | #pragma mark - NSCopying 330 | 331 | - (instancetype)copyWithZone:(NSZone *)zone { 332 | AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; 333 | securityPolicy.SSLPinningMode = self.SSLPinningMode; 334 | securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; 335 | securityPolicy.validatesDomainName = self.validatesDomainName; 336 | securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; 337 | 338 | return securityPolicy; 339 | } 340 | 341 | @end 342 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | // AFURLResponseSerialization.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | Recursively removes `NSNull` values from a JSON object. 29 | */ 30 | FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions); 31 | 32 | /** 33 | The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. 34 | 35 | For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. 36 | */ 37 | @protocol AFURLResponseSerialization 38 | 39 | /** 40 | The response object decoded from the data associated with a specified response. 41 | 42 | @param response The response to be processed. 43 | @param data The response data to be decoded. 44 | @param error The error that occurred while attempting to decode the response data. 45 | 46 | @return The object decoded from the specified response data. 47 | */ 48 | - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response 49 | data:(nullable NSData *)data 50 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; 51 | 52 | @end 53 | 54 | #pragma mark - 55 | 56 | /** 57 | `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. 58 | 59 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. 60 | */ 61 | @interface AFHTTPResponseSerializer : NSObject 62 | 63 | - (instancetype)init; 64 | 65 | /** 66 | Creates and returns a serializer with default configuration. 67 | */ 68 | + (instancetype)serializer; 69 | 70 | ///----------------------------------------- 71 | /// @name Configuring Response Serialization 72 | ///----------------------------------------- 73 | 74 | /** 75 | The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. 76 | 77 | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 78 | */ 79 | @property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; 80 | 81 | /** 82 | The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. 83 | */ 84 | @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; 85 | 86 | /** 87 | Validates the specified response and data. 88 | 89 | In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. 90 | 91 | @param response The response to be validated. 92 | @param data The data associated with the response. 93 | @param error The error that occurred while attempting to validate the response. 94 | 95 | @return `YES` if the response is valid, otherwise `NO`. 96 | */ 97 | - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response 98 | data:(nullable NSData *)data 99 | error:(NSError * _Nullable __autoreleasing *)error; 100 | 101 | @end 102 | 103 | #pragma mark - 104 | 105 | 106 | /** 107 | `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. 108 | 109 | By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 110 | 111 | - `application/json` 112 | - `text/json` 113 | - `text/javascript` 114 | 115 | In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details. 116 | */ 117 | @interface AFJSONResponseSerializer : AFHTTPResponseSerializer 118 | 119 | - (instancetype)init; 120 | 121 | /** 122 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 123 | */ 124 | @property (nonatomic, assign) NSJSONReadingOptions readingOptions; 125 | 126 | /** 127 | Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. 128 | */ 129 | @property (nonatomic, assign) BOOL removesKeysWithNullValues; 130 | 131 | /** 132 | Creates and returns a JSON serializer with specified reading and writing options. 133 | 134 | @param readingOptions The specified JSON reading options. 135 | */ 136 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; 137 | 138 | @end 139 | 140 | #pragma mark - 141 | 142 | /** 143 | `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. 144 | 145 | By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 146 | 147 | - `application/xml` 148 | - `text/xml` 149 | */ 150 | @interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer 151 | 152 | @end 153 | 154 | #pragma mark - 155 | 156 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 157 | 158 | /** 159 | `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 160 | 161 | By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 162 | 163 | - `application/xml` 164 | - `text/xml` 165 | */ 166 | @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer 167 | 168 | - (instancetype)init; 169 | 170 | /** 171 | Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default. 172 | */ 173 | @property (nonatomic, assign) NSUInteger options; 174 | 175 | /** 176 | Creates and returns an XML document serializer with the specified options. 177 | 178 | @param mask The XML document options. 179 | */ 180 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; 181 | 182 | @end 183 | 184 | #endif 185 | 186 | #pragma mark - 187 | 188 | /** 189 | `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 190 | 191 | By default, `AFPropertyListResponseSerializer` accepts the following MIME types: 192 | 193 | - `application/x-plist` 194 | */ 195 | @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer 196 | 197 | - (instancetype)init; 198 | 199 | /** 200 | The property list format. Possible values are described in "NSPropertyListFormat". 201 | */ 202 | @property (nonatomic, assign) NSPropertyListFormat format; 203 | 204 | /** 205 | The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." 206 | */ 207 | @property (nonatomic, assign) NSPropertyListReadOptions readOptions; 208 | 209 | /** 210 | Creates and returns a property list serializer with a specified format, read options, and write options. 211 | 212 | @param format The property list format. 213 | @param readOptions The property list reading options. 214 | */ 215 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 216 | readOptions:(NSPropertyListReadOptions)readOptions; 217 | 218 | @end 219 | 220 | #pragma mark - 221 | 222 | /** 223 | `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. 224 | 225 | By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 226 | 227 | - `image/tiff` 228 | - `image/jpeg` 229 | - `image/gif` 230 | - `image/png` 231 | - `image/ico` 232 | - `image/x-icon` 233 | - `image/bmp` 234 | - `image/x-bmp` 235 | - `image/x-xbitmap` 236 | - `image/x-win-bitmap` 237 | */ 238 | @interface AFImageResponseSerializer : AFHTTPResponseSerializer 239 | 240 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 241 | /** 242 | The scale factor used when interpreting the image data to construct `responseImage`. Specifying 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. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. 243 | */ 244 | @property (nonatomic, assign) CGFloat imageScale; 245 | 246 | /** 247 | Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. 248 | */ 249 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; 250 | #endif 251 | 252 | @end 253 | 254 | #pragma mark - 255 | 256 | /** 257 | `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. 258 | */ 259 | @interface AFCompoundResponseSerializer : AFHTTPResponseSerializer 260 | 261 | /** 262 | The component response serializers. 263 | */ 264 | @property (readonly, nonatomic, copy) NSArray > *responseSerializers; 265 | 266 | /** 267 | Creates and returns a compound serializer comprised of the specified response serializers. 268 | 269 | @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. 270 | */ 271 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; 272 | 273 | @end 274 | 275 | ///---------------- 276 | /// @name Constants 277 | ///---------------- 278 | 279 | /** 280 | ## Error Domains 281 | 282 | The following error domain is predefined. 283 | 284 | - `NSString * const AFURLResponseSerializationErrorDomain` 285 | 286 | ### Constants 287 | 288 | `AFURLResponseSerializationErrorDomain` 289 | AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. 290 | */ 291 | FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; 292 | 293 | /** 294 | ## User info dictionary keys 295 | 296 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 297 | 298 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 299 | - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` 300 | 301 | ### Constants 302 | 303 | `AFNetworkingOperationFailingURLResponseErrorKey` 304 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 305 | 306 | `AFNetworkingOperationFailingURLResponseDataErrorKey` 307 | The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 308 | */ 309 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 310 | 311 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; 312 | 313 | NS_ASSUME_NONNULL_END 314 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /Demo/Pods/AFNetworking/README.md: -------------------------------------------------------------------------------- 1 |

2 | AFNetworking 3 |

4 | 5 | [![Build Status](https://github.com/AFNetworking/AFNetworking/workflows/AFNetworking%20CI/badge.svg?branch=master)](https://github.com/AFNetworking/AFNetworking/actions) 6 | [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) 7 | [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) 8 | [![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) 9 | [![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) 10 | 11 | AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. 12 | 13 | Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. 14 | 15 | ## How To Get Started 16 | 17 | - [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps 18 | - Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) 19 | 20 | ## Communication 21 | 22 | - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') 23 | - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). 24 | - If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. 25 | - If you **have a feature request**, open an issue. 26 | - If you **want to contribute**, submit a pull request. 27 | 28 | ## Installation 29 | AFNetworking supports multiple methods for installing the library in a project. 30 | 31 | ## Installation with CocoaPods 32 | 33 | To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: 34 | 35 | ```ruby 36 | pod 'AFNetworking', '~> 4.0' 37 | ``` 38 | 39 | ### Installation with Swift Package Manager 40 | 41 | Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. 42 | 43 | ```swift 44 | dependencies: [ 45 | .package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0")) 46 | ] 47 | ``` 48 | 49 | > Note: AFNetworking's Swift package does not include it's UIKit extensions. 50 | 51 | ### Installation with Carthage 52 | 53 | [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your `Cartfile`. 54 | 55 | ```ogdl 56 | github "AFNetworking/AFNetworking" ~> 4.0 57 | ``` 58 | 59 | ## Requirements 60 | 61 | | AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes | 62 | |:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| 63 | | 4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. | 64 | | 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | 65 | | 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | 66 | | 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | 67 | | 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | 68 | | 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | 69 | 70 | (macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). 71 | 72 | > Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. 73 | 74 | ## Architecture 75 | 76 | ### NSURLSession 77 | 78 | - `AFURLSessionManager` 79 | - `AFHTTPSessionManager` 80 | 81 | ### Serialization 82 | 83 | * `` 84 | - `AFHTTPRequestSerializer` 85 | - `AFJSONRequestSerializer` 86 | - `AFPropertyListRequestSerializer` 87 | * `` 88 | - `AFHTTPResponseSerializer` 89 | - `AFJSONResponseSerializer` 90 | - `AFXMLParserResponseSerializer` 91 | - `AFXMLDocumentResponseSerializer` _(macOS)_ 92 | - `AFPropertyListResponseSerializer` 93 | - `AFImageResponseSerializer` 94 | - `AFCompoundResponseSerializer` 95 | 96 | ### Additional Functionality 97 | 98 | - `AFSecurityPolicy` 99 | - `AFNetworkReachabilityManager` 100 | 101 | ## Usage 102 | 103 | ### AFURLSessionManager 104 | 105 | `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. 106 | 107 | #### Creating a Download Task 108 | 109 | ```objective-c 110 | NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 111 | AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 112 | 113 | NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; 114 | NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 115 | 116 | NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 117 | NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 118 | return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 119 | } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 120 | NSLog(@"File downloaded to: %@", filePath); 121 | }]; 122 | [downloadTask resume]; 123 | ``` 124 | 125 | #### Creating an Upload Task 126 | 127 | ```objective-c 128 | NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 129 | AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 130 | 131 | NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; 132 | NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 133 | 134 | NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; 135 | NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 136 | if (error) { 137 | NSLog(@"Error: %@", error); 138 | } else { 139 | NSLog(@"Success: %@ %@", response, responseObject); 140 | } 141 | }]; 142 | [uploadTask resume]; 143 | ``` 144 | 145 | #### Creating an Upload Task for a Multi-Part Request, with Progress 146 | 147 | ```objective-c 148 | NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { 149 | [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 150 | } error:nil]; 151 | 152 | AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 153 | 154 | NSURLSessionUploadTask *uploadTask; 155 | uploadTask = [manager 156 | uploadTaskWithStreamedRequest:request 157 | progress:^(NSProgress * _Nonnull uploadProgress) { 158 | // This is not called back on the main queue. 159 | // You are responsible for dispatching to the main queue for UI updates 160 | dispatch_async(dispatch_get_main_queue(), ^{ 161 | //Update the progress view 162 | [progressView setProgress:uploadProgress.fractionCompleted]; 163 | }); 164 | } 165 | completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 166 | if (error) { 167 | NSLog(@"Error: %@", error); 168 | } else { 169 | NSLog(@"%@ %@", response, responseObject); 170 | } 171 | }]; 172 | 173 | [uploadTask resume]; 174 | ``` 175 | 176 | #### Creating a Data Task 177 | 178 | ```objective-c 179 | NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 180 | AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 181 | 182 | NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; 183 | NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 184 | 185 | NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 186 | if (error) { 187 | NSLog(@"Error: %@", error); 188 | } else { 189 | NSLog(@"%@ %@", response, responseObject); 190 | } 191 | }]; 192 | [dataTask resume]; 193 | ``` 194 | 195 | --- 196 | 197 | ### Request Serialization 198 | 199 | Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. 200 | 201 | ```objective-c 202 | NSString *URLString = @"http://example.com"; 203 | NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; 204 | ``` 205 | 206 | #### Query String Parameter Encoding 207 | 208 | ```objective-c 209 | [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; 210 | ``` 211 | 212 | GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 213 | 214 | #### URL Form Parameter Encoding 215 | 216 | ```objective-c 217 | [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; 218 | ``` 219 | 220 | POST http://example.com/ 221 | Content-Type: application/x-www-form-urlencoded 222 | 223 | foo=bar&baz[]=1&baz[]=2&baz[]=3 224 | 225 | #### JSON Parameter Encoding 226 | 227 | ```objective-c 228 | [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; 229 | ``` 230 | 231 | POST http://example.com/ 232 | Content-Type: application/json 233 | 234 | {"foo": "bar", "baz": [1,2,3]} 235 | 236 | --- 237 | 238 | ### Network Reachability Manager 239 | 240 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 241 | 242 | * Do not use Reachability to determine if the original request should be sent. 243 | * You should try to send it. 244 | * You can use Reachability to determine when a request should be automatically retried. 245 | * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. 246 | * Network reachability is a useful tool for determining why a request might have failed. 247 | * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." 248 | 249 | See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). 250 | 251 | #### Shared Network Reachability 252 | 253 | ```objective-c 254 | [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 255 | NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); 256 | }]; 257 | 258 | [[AFNetworkReachabilityManager sharedManager] startMonitoring]; 259 | ``` 260 | 261 | --- 262 | 263 | ### Security Policy 264 | 265 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 266 | 267 | Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. 268 | 269 | #### Allowing Invalid SSL Certificates 270 | 271 | ```objective-c 272 | AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 273 | manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production 274 | ``` 275 | 276 | --- 277 | 278 | ## Unit Tests 279 | 280 | AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. 281 | 282 | ## Credits 283 | 284 | AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). 285 | 286 | AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). 287 | 288 | AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). 289 | 290 | And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). 291 | 292 | ### Security Disclosure 293 | 294 | If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. 295 | 296 | ## License 297 | 298 | AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details. 299 | -------------------------------------------------------------------------------- /Demo/Pods/Manifest.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - AFNetworking/NSURLSession (4.0.1): 3 | - AFNetworking/Reachability 4 | - AFNetworking/Security 5 | - AFNetworking/Serialization 6 | - AFNetworking/Reachability (4.0.1) 7 | - AFNetworking/Security (4.0.1) 8 | - AFNetworking/Serialization (4.0.1) 9 | 10 | DEPENDENCIES: 11 | - AFNetworking/NSURLSession 12 | 13 | SPEC REPOS: 14 | trunk: 15 | - AFNetworking 16 | 17 | SPEC CHECKSUMS: 18 | AFNetworking: 7864c38297c79aaca1500c33288e429c3451fdce 19 | 20 | PODFILE CHECKSUM: 041567286b2264d827f24eed23468038119cf51b 21 | 22 | COCOAPODS: 1.8.4 23 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${PRODUCT_BUNDLE_IDENTIFIER} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 4.0.1 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | ${CURRENT_PROJECT_VERSION} 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_AFNetworking : NSObject 3 | @end 4 | @implementation PodsDummy_AFNetworking 5 | @end 6 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | #import "AFHTTPSessionManager.h" 14 | #import "AFURLSessionManager.h" 15 | #import "AFCompatibilityMacros.h" 16 | #import "AFNetworkReachabilityManager.h" 17 | #import "AFSecurityPolicy.h" 18 | #import "AFURLRequestSerialization.h" 19 | #import "AFURLResponseSerialization.h" 20 | 21 | FOUNDATION_EXPORT double AFNetworkingVersionNumber; 22 | FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; 23 | 24 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap: -------------------------------------------------------------------------------- 1 | framework module AFNetworking { 2 | umbrella header "AFNetworking-umbrella.h" 3 | 4 | export * 5 | module * { export * } 6 | } 7 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig: -------------------------------------------------------------------------------- 1 | CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | PODS_BUILD_DIR = ${BUILD_DIR} 4 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 5 | PODS_ROOT = ${SRCROOT} 6 | PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFNetworking 7 | PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking 8 | SKIP_INSTALL = YES 9 | USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES 10 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${PRODUCT_BUNDLE_IDENTIFIER} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | ${CURRENT_PROJECT_VERSION} 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-acknowledgements.markdown: -------------------------------------------------------------------------------- 1 | # Acknowledgements 2 | This application makes use of the following third party libraries: 3 | 4 | ## AFNetworking 5 | 6 | Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | 26 | Generated by CocoaPods - https://cocoapods.org 27 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-acknowledgements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreferenceSpecifiers 6 | 7 | 8 | FooterText 9 | This application makes use of the following third party libraries: 10 | Title 11 | Acknowledgements 12 | Type 13 | PSGroupSpecifier 14 | 15 | 16 | FooterText 17 | Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | 37 | License 38 | MIT 39 | Title 40 | AFNetworking 41 | Type 42 | PSGroupSpecifier 43 | 44 | 45 | FooterText 46 | Generated by CocoaPods - https://cocoapods.org 47 | Title 48 | 49 | Type 50 | PSGroupSpecifier 51 | 52 | 53 | StringsTable 54 | Acknowledgements 55 | Title 56 | Acknowledgements 57 | 58 | 59 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_Pods_LCWebImage : NSObject 3 | @end 4 | @implementation PodsDummy_Pods_LCWebImage 5 | @end 6 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks-Debug-input-files.xcfilelist: -------------------------------------------------------------------------------- 1 | ${PODS_ROOT}/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks.sh 2 | ${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks-Debug-output-files.xcfilelist: -------------------------------------------------------------------------------- 1 | ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks-Release-input-files.xcfilelist: -------------------------------------------------------------------------------- 1 | ${PODS_ROOT}/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks.sh 2 | ${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks-Release-output-files.xcfilelist: -------------------------------------------------------------------------------- 1 | ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-frameworks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | set -u 4 | set -o pipefail 5 | 6 | function on_error { 7 | echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" 8 | } 9 | trap 'on_error $LINENO' ERR 10 | 11 | if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then 12 | # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy 13 | # frameworks to, so exit 0 (signalling the script phase was successful). 14 | exit 0 15 | fi 16 | 17 | echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 18 | mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 19 | 20 | COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" 21 | SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" 22 | 23 | # Used as a return value for each invocation of `strip_invalid_archs` function. 24 | STRIP_BINARY_RETVAL=0 25 | 26 | # This protects against multiple targets copying the same framework dependency at the same time. The solution 27 | # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html 28 | RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") 29 | 30 | # Copies and strips a vendored framework 31 | install_framework() 32 | { 33 | if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then 34 | local source="${BUILT_PRODUCTS_DIR}/$1" 35 | elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then 36 | local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" 37 | elif [ -r "$1" ]; then 38 | local source="$1" 39 | fi 40 | 41 | local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 42 | 43 | if [ -L "${source}" ]; then 44 | echo "Symlinked..." 45 | source="$(readlink "${source}")" 46 | fi 47 | 48 | # Use filter instead of exclude so missing patterns don't throw errors. 49 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" 50 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" 51 | 52 | local basename 53 | basename="$(basename -s .framework "$1")" 54 | binary="${destination}/${basename}.framework/${basename}" 55 | 56 | if ! [ -r "$binary" ]; then 57 | binary="${destination}/${basename}" 58 | elif [ -L "${binary}" ]; then 59 | echo "Destination binary is symlinked..." 60 | dirname="$(dirname "${binary}")" 61 | binary="${dirname}/$(readlink "${binary}")" 62 | fi 63 | 64 | # Strip invalid architectures so "fat" simulator / device frameworks work on device 65 | if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then 66 | strip_invalid_archs "$binary" 67 | fi 68 | 69 | # Resign the code if required by the build settings to avoid unstable apps 70 | code_sign_if_enabled "${destination}/$(basename "$1")" 71 | 72 | # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. 73 | if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then 74 | local swift_runtime_libs 75 | swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) 76 | for lib in $swift_runtime_libs; do 77 | echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" 78 | rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" 79 | code_sign_if_enabled "${destination}/${lib}" 80 | done 81 | fi 82 | } 83 | 84 | # Copies and strips a vendored dSYM 85 | install_dsym() { 86 | local source="$1" 87 | if [ -r "$source" ]; then 88 | # Copy the dSYM into a the targets temp dir. 89 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" 90 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" 91 | 92 | local basename 93 | basename="$(basename -s .framework.dSYM "$source")" 94 | binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" 95 | 96 | # Strip invalid architectures so "fat" simulator / device frameworks work on device 97 | if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then 98 | strip_invalid_archs "$binary" 99 | fi 100 | 101 | if [[ $STRIP_BINARY_RETVAL == 1 ]]; then 102 | # Move the stripped file into its final destination. 103 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" 104 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" 105 | else 106 | # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. 107 | touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" 108 | fi 109 | fi 110 | } 111 | 112 | # Copies the bcsymbolmap files of a vendored framework 113 | install_bcsymbolmap() { 114 | local bcsymbolmap_path="$1" 115 | local destination="${BUILT_PRODUCTS_DIR}" 116 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" 117 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" 118 | } 119 | 120 | # Signs a framework with the provided identity 121 | code_sign_if_enabled() { 122 | if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then 123 | # Use the current code_sign_identity 124 | echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" 125 | local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" 126 | 127 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 128 | code_sign_cmd="$code_sign_cmd &" 129 | fi 130 | echo "$code_sign_cmd" 131 | eval "$code_sign_cmd" 132 | fi 133 | } 134 | 135 | # Strip invalid architectures 136 | strip_invalid_archs() { 137 | binary="$1" 138 | # Get architectures for current target binary 139 | binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" 140 | # Intersect them with the architectures we are building for 141 | intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" 142 | # If there are no archs supported by this binary then warn the user 143 | if [[ -z "$intersected_archs" ]]; then 144 | echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." 145 | STRIP_BINARY_RETVAL=0 146 | return 147 | fi 148 | stripped="" 149 | for arch in $binary_archs; do 150 | if ! [[ "${ARCHS}" == *"$arch"* ]]; then 151 | # Strip non-valid architectures in-place 152 | lipo -remove "$arch" -output "$binary" "$binary" 153 | stripped="$stripped $arch" 154 | fi 155 | done 156 | if [[ "$stripped" ]]; then 157 | echo "Stripped $binary of architectures:$stripped" 158 | fi 159 | STRIP_BINARY_RETVAL=1 160 | } 161 | 162 | 163 | if [[ "$CONFIGURATION" == "Debug" ]]; then 164 | install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" 165 | fi 166 | if [[ "$CONFIGURATION" == "Release" ]]; then 167 | install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" 168 | fi 169 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 170 | wait 171 | fi 172 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage-umbrella.h: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | 14 | FOUNDATION_EXPORT double Pods_LCWebImageVersionNumber; 15 | FOUNDATION_EXPORT const unsigned char Pods_LCWebImageVersionString[]; 16 | 17 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage.debug.xcconfig: -------------------------------------------------------------------------------- 1 | FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" 4 | LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' 5 | OTHER_LDFLAGS = $(inherited) -framework "AFNetworking" 6 | PODS_BUILD_DIR = ${BUILD_DIR} 7 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 8 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 9 | PODS_ROOT = ${SRCROOT}/Pods 10 | USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES 11 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage.modulemap: -------------------------------------------------------------------------------- 1 | framework module Pods_LCWebImage { 2 | umbrella header "Pods-LCWebImage-umbrella.h" 3 | 4 | export * 5 | module * { export * } 6 | } 7 | -------------------------------------------------------------------------------- /Demo/Pods/Target Support Files/Pods-LCWebImage/Pods-LCWebImage.release.xcconfig: -------------------------------------------------------------------------------- 1 | FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" 4 | LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' 5 | OTHER_LDFLAGS = $(inherited) -framework "AFNetworking" 6 | PODS_BUILD_DIR = ${BUILD_DIR} 7 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 8 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 9 | PODS_ROOT = ${SRCROOT}/Pods 10 | USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES 11 | -------------------------------------------------------------------------------- /LCWebImage.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = "LCWebImage" 3 | s.version = "1.1.0" 4 | s.summary = "一个基于AFNetworking实现的轻量级异步图片加载框架,支持内存和磁盘缓存,同时提供了自定义缓存、自定义图片解码、自定义网络配置等功能。" 5 | s.homepage = "https://github.com/iLiuChang/LCWebImage" 6 | s.license = "MIT" 7 | s.author = "LiuChang" 8 | s.platform = :ios, "9.0" 9 | s.source = { :git => "https://github.com/iLiuChang/LCWebImage.git", :tag => s.version } 10 | s.requires_arc = true 11 | s.source_files = "LCWebImage/*.{h,m}" 12 | s.requires_arc = true 13 | s.dependency 'AFNetworking/NSURLSession', '~> 4.0' 14 | end -------------------------------------------------------------------------------- /LCWebImage/LCAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | // LCAutoPurgingImageCache.h 2 | // 3 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 4 | // 5 | // Created by 刘畅 on 2022/5/12. 6 | // Copyright © 2022 LiuChang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | /// Image Cache Expire Type 14 | typedef NS_ENUM(NSUInteger, LCImageDiskCacheExpireType) { 15 | /** 16 | * When the image cache is accessed it will update this value 17 | */ 18 | LCImageDiskCacheExpireTypeAccessDate, 19 | /** 20 | * When the image cache is created or modified it will update this value (Default) 21 | */ 22 | LCImageDiskCacheExpireTypeModificationDate, 23 | /** 24 | * When the image cache is created it will update this value 25 | */ 26 | LCImageDiskCacheExpireTypeCreationDate, 27 | /** 28 | * When the image cache is created, modified, renamed, file attribute updated (like permission, xattr) it will update this value 29 | */ 30 | LCImageDiskCacheExpireTypeChangeDate, 31 | }; 32 | 33 | /** 34 | The `LCImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. 35 | */ 36 | @protocol LCImageCache 37 | 38 | /** 39 | The decoded image. 40 | 41 | @param data The origin data. 42 | @param identifier The unique identifier for the image in the cache. 43 | 44 | @return An image for the data, or nil. 45 | */ 46 | - (nullable UIImage *)decodedImageFromData:(nullable NSData *)data withIdentifier:(NSString *)identifier; 47 | 48 | /** 49 | Adds the image to the cache with the given identifier. 50 | 51 | @param image The image to cache. 52 | @param identifier The unique identifier for the image in the cache. 53 | */ 54 | - (void)addMemoryImage:(nullable UIImage *)image withIdentifier:(NSString *)identifier; 55 | 56 | /** 57 | Removes the image from the cache matching the given identifier. 58 | 59 | @param identifier The unique identifier for the image in the cache. 60 | 61 | @return A BOOL indicating whether or not the image was removed from the cache. 62 | */ 63 | - (BOOL)removeMemoryImageWithIdentifier:(NSString *)identifier; 64 | 65 | /** 66 | Returns the image in the cache associated with the given identifier. 67 | 68 | @param identifier The unique identifier for the image in the cache. 69 | 70 | @return An image for the matching identifier, or nil. 71 | */ 72 | - (nullable UIImage *)memoryImageWithIdentifier:(NSString *)identifier; 73 | 74 | /** 75 | Returns a boolean value that indicates whether a given identifier is in cache. 76 | This method may blocks the calling thread until file read finished. 77 | 78 | @param identifier A string identifying the data. If nil, just return NO. 79 | @return Whether the identifier is in cache. 80 | */ 81 | - (BOOL)containsDiskDataWithIdentifier:(NSString *)identifier; 82 | 83 | /** 84 | Returns the data associated with a given identifier. 85 | This method may blocks the calling thread until file read finished. 86 | 87 | @param identifier A string identifying the data. If nil, just return nil. 88 | @return The value associated with identifier, or nil if no value is associated with identifier. 89 | */ 90 | - (nullable NSData *)diskDataWithIdentifier:(NSString *)identifier; 91 | 92 | /** 93 | Sets the value of the specified identifier in the cache. 94 | This method may blocks the calling thread until file write finished. 95 | 96 | @param data The data to be stored in the cache. 97 | @param identifier The identifier with which to associate the value. If nil, this method has no effect. 98 | */ 99 | - (void)addDiskData:(nullable NSData *)data withIdentifier:(NSString *)identifier; 100 | 101 | /** 102 | Removes the value of the specified key in the cache. 103 | This method may blocks the calling thread until file delete finished. 104 | 105 | @param identifier The value to be removed. If nil, this method has no effect. 106 | */ 107 | - (void)removeDiskDataWithIdentifier:(nonnull NSString *)identifier; 108 | @end 109 | 110 | /** 111 | The built-in disk cache. 112 | */ 113 | @interface LCImageDiskCache : NSObject 114 | 115 | /** 116 | * Whether or not to disable iCloud backup 117 | * Defaults to YES. 118 | */ 119 | @property (assign, nonatomic) BOOL shouldDisableiCloud; 120 | 121 | /* 122 | * The attribute which the clear cache will be checked against when clearing the disk cache 123 | * Default is Modified Date 124 | */ 125 | @property (assign, nonatomic) LCImageDiskCacheExpireType diskCacheExpireType; 126 | 127 | /** 128 | * The maximum length of time to keep an image in the disk cache, in seconds. 129 | * Setting this to a negative value means no expiring. 130 | * Setting this to zero means that all cached files would be removed when do expiration check. 131 | * Defaults to 1 week. 132 | */ 133 | @property (assign, nonatomic) NSTimeInterval maxDiskAge; 134 | 135 | /** 136 | * The maximum size of the disk cache, in bytes. 137 | * Defaults to 0. Which means there is no cache size limit. 138 | */ 139 | @property (assign, nonatomic) NSUInteger maxDiskSize; 140 | 141 | /** 142 | * Whether or not to remove the expired disk data when application entering the background. 143 | * Defaults to YES. 144 | */ 145 | @property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground; 146 | 147 | /** 148 | * Whether or not to remove the expired disk data when application been terminated. This operation is processed in sync to ensure clean up. 149 | * Defaults to YES. 150 | */ 151 | @property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenTerminate; 152 | 153 | /** 154 | Create a new disk cache based on the specified path. You can check `maxDiskSize` and `maxDiskAge` used for disk cache. 155 | 156 | @param cachePath Full path of a directory in which the cache will write data. 157 | Once initialized you should not read and write to this directory. 158 | 159 | @return A new cache object, or nil if an error occurs. 160 | */ 161 | - (nullable instancetype)initWithCachePath:(NSString *)cachePath; 162 | 163 | /** 164 | Returns a boolean value that indicates whether a given identifier is in cache. 165 | This method may blocks the calling thread until file read finished. 166 | 167 | @param identifier A string identifying the data. If nil, just return NO. 168 | @return Whether the identifier is in cache. 169 | */ 170 | - (BOOL)containsDataWithIdentifier:(NSString *)identifier; 171 | 172 | /** 173 | Returns the data associated with a given identifier. 174 | This method may blocks the calling thread until file read finished. 175 | 176 | @param identifier A string identifying the data. If nil, just return nil. 177 | @return The value associated with identifier, or nil if no value is associated with identifier. 178 | */ 179 | - (nullable NSData *)dataWithIdentifier:(NSString *)identifier; 180 | 181 | /** 182 | Sets the value of the specified identifier in the cache. 183 | This method may blocks the calling thread until file write finished. 184 | 185 | @param data The data to be stored in the cache. 186 | @param identifier The identifier with which to associate the value. If nil, this method has no effect. 187 | */ 188 | - (void)addData:(nullable NSData *)data withIdentifier:(NSString *)identifier; 189 | 190 | /** 191 | Removes the value of the specified key in the cache. 192 | This method may blocks the calling thread until file delete finished. 193 | 194 | @param identifier The value to be removed. If nil, this method has no effect. 195 | */ 196 | - (void)removeDataWithIdentifier:(nonnull NSString *)identifier; 197 | 198 | /** 199 | Empties the cache. 200 | This method may blocks the calling thread until file delete finished. 201 | */ 202 | - (void)removeAllData; 203 | 204 | /** 205 | The cache path for identifier 206 | 207 | @param identifier A string identifying the value 208 | @return The cache path for identifier. Or nil if the identifier can not associate to a path 209 | */ 210 | - (nullable NSString *)cachePathWithIdentifier:(nonnull NSString *)identifier; 211 | 212 | /** 213 | Returns the number of data in this cache. 214 | This method may blocks the calling thread until file read finished. 215 | 216 | @return The total data count. 217 | */ 218 | - (NSUInteger)totalCount; 219 | 220 | /** 221 | Returns the total size (in bytes) of data in this cache. 222 | This method may blocks the calling thread until file read finished. 223 | 224 | @return The total data size in bytes. 225 | */ 226 | - (NSUInteger)totalSize; 227 | 228 | /** 229 | Removes the expired data from the cache. You can choose the data to remove base on `ageLimit`, `countLimit` and `sizeLimit` options. 230 | */ 231 | - (void)removeExpiredData; 232 | 233 | @end 234 | 235 | /** 236 | The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. 237 | */ 238 | @interface LCAutoPurgingImageCache : NSObject 239 | 240 | /** 241 | The disk cache. 242 | */ 243 | @property (nonatomic, strong, nullable) LCImageDiskCache *diskCache; 244 | 245 | /** 246 | Customize the decoded image. 247 | */ 248 | @property (nonatomic, copy, nullable) UIImage * (^customDecodedImage)(NSData *data, NSString *identifier); 249 | 250 | /** 251 | The total memory capacity of the cache in bytes. 252 | */ 253 | @property (nonatomic, assign) UInt64 memoryCapacity; 254 | 255 | /** 256 | The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. 257 | */ 258 | @property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; 259 | 260 | /** 261 | The current total memory usage in bytes of all images stored within the cache. 262 | */ 263 | @property (nonatomic, assign, readonly) UInt64 memoryUsage; 264 | 265 | /** 266 | Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. 267 | 268 | @return The new `AutoPurgingImageCache` instance. 269 | */ 270 | - (instancetype)init; 271 | 272 | /** 273 | Removes all images from the cache. 274 | 275 | @return A BOOL indicating whether or not all images were removed from the cache. 276 | */ 277 | - (BOOL)removeAllMemoryImages; 278 | 279 | /** 280 | Adds the image to the cache with the given identifier. 281 | 282 | @param image The image to cache. 283 | @param data The image to cache. 284 | @param identifier The unique identifier for the image in the cache. 285 | */ 286 | - (void)addImage:(nullable UIImage *)image imageData:(NSData *)data withIdentifier:(NSString *)identifier; 287 | 288 | /** 289 | Removes the image from the cache matching the given identifier. 290 | 291 | @param identifier The unique identifier for the image in the cache. 292 | */ 293 | - (void)removeImageWithIdentifier:(NSString *)identifier; 294 | 295 | /** 296 | Removes all images from the cache. 297 | 298 | */ 299 | - (void)removeAllImages; 300 | 301 | /** 302 | Returns the image in the cache associated with the given identifier. 303 | 304 | @param identifier The unique identifier for the image in the cache. 305 | 306 | @return An image for the matching identifier, or nil. 307 | */ 308 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; 309 | @end 310 | 311 | NS_ASSUME_NONNULL_END 312 | 313 | -------------------------------------------------------------------------------- /LCWebImage/LCWebImageManager.h: -------------------------------------------------------------------------------- 1 | // LCWebImageManager.h 2 | // 3 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 4 | // 5 | // Created by 刘畅 on 2022/5/12. 6 | // Copyright © 2022 LiuChang. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "LCAutoPurgingImageCache.h" 11 | #if __has_include() 12 | #import 13 | #else 14 | #import "AFHTTPSessionManager.h" 15 | #endif 16 | 17 | NS_ASSUME_NONNULL_BEGIN 18 | 19 | typedef NS_ENUM(NSInteger, LCImageDownloadPrioritization) { 20 | LCImageDownloadPrioritizationFIFO, 21 | LCImageDownloadPrioritizationLIFO 22 | }; 23 | 24 | /// The options to control image operation. 25 | typedef NS_OPTIONS(NSUInteger, LCWebImageOptions) { 26 | 27 | /// Do not load image from/to disk cache. 28 | LCWebImageOptionIgnoreDiskCache = 1 << 0, 29 | 30 | /// If the returned image is empty, use the placeHolder. 31 | LCWebImageOptionNilImageUsePlaceHolder = 1 << 1, 32 | }; 33 | 34 | /** 35 | The `LCImageDownloadReceipt` is an object vended by the `LCWebImageManager` when starting a data task. It can be used to cancel active tasks running on the `LCWebImageManager` session. As a general rule, image data tasks should be cancelled using the `LCImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `LCWebImageManager` is optimized to handle duplicate task scenarios as well as pending versus active downloads. 36 | */ 37 | @interface LCImageDownloadReceipt : NSObject 38 | 39 | @property (nonatomic, strong) NSURL *url; 40 | 41 | /** 42 | The data task created by the `LCWebImageManager`. 43 | */ 44 | @property (nonatomic, strong, nullable) NSURLSessionDataTask *task; 45 | 46 | /** 47 | The unique identifier for the success and failure blocks when duplicate requests are made. 48 | */ 49 | @property (nonatomic, strong) NSUUID *receiptID; 50 | @end 51 | 52 | /** The `LCWebImageManager` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. 53 | */ 54 | @interface LCWebImageManager : NSObject 55 | 56 | /** 57 | The image cache used to store all downloaded images in. `LCAutoPurgingImageCache` by default. 58 | */ 59 | @property (nonatomic, strong, readonly) id imageCache; 60 | 61 | /** 62 | The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. 63 | */ 64 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager; 65 | 66 | /** 67 | Defines the order prioritization of incoming download requests being inserted into the queue. `LCImageDownloadPrioritizationFIFO` by default. 68 | */ 69 | @property (nonatomic, assign) LCImageDownloadPrioritization downloadPrioritization; 70 | 71 | /** 72 | The shared default instance of `LCWebImageManager` initialized with default values. 73 | */ 74 | + (instancetype)defaultInstance; 75 | 76 | /** 77 | Creates a default `NSURLCache` with common usage parameter values. 78 | 79 | @returns The default `NSURLCache` instance. 80 | */ 81 | + (NSURLCache *)defaultURLCache; 82 | 83 | /** 84 | The default `NSURLSessionConfiguration` with common usage parameter values. 85 | */ 86 | + (NSURLSessionConfiguration *)defaultURLSessionConfiguration; 87 | 88 | /** 89 | Default initializer 90 | 91 | @return An instance of `LCWebImageManager` initialized with default values. 92 | */ 93 | - (instancetype)init; 94 | 95 | /** 96 | Initializer with specific `URLSessionConfiguration` 97 | 98 | @param configuration The `NSURLSessionConfiguration` to be be used 99 | 100 | @return An instance of `LCWebImageManager` initialized with default values and custom `NSURLSessionConfiguration` 101 | */ 102 | - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; 103 | 104 | /** 105 | Initializes the `LCWebImageManager` instance with the given session manager, download prioritization, maximum active download count and image cache. 106 | 107 | @param sessionManager The session manager to use to download images. 108 | @param downloadPrioritization The download prioritization of the download queue. 109 | @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. 110 | @param imageCache The image cache used to store all downloaded images in. 111 | 112 | @return The new `LCWebImageManager` instance. 113 | */ 114 | - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager 115 | downloadPrioritization:(LCImageDownloadPrioritization)downloadPrioritization 116 | maximumActiveDownloads:(NSInteger)maximumActiveDownloads 117 | imageCache:(nullable id )imageCache; 118 | 119 | /** 120 | The disk image. 121 | 122 | @param URL The URL. 123 | @param receiptID The options to control image operation. 124 | @param completion A block to be executed when the image data task finished. 125 | 126 | @return LCImageDownloadReceipt. 127 | */ 128 | 129 | - (nullable LCImageDownloadReceipt *)diskImageForURL:(NSURL *)URL 130 | withReceiptID:(nonnull NSUUID *)receiptID 131 | completion:(nullable void (^)(UIImage *image))completion; 132 | 133 | /** 134 | Creates a data task using the `sessionManager` instance for the specified URL request. 135 | 136 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 137 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 138 | task are executed in the order they were added. 139 | 140 | @param request The URL request. 141 | @param options The options to control image operation. 142 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 143 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 144 | 145 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 146 | cache and the URL request cache policy allows the cache to be used. 147 | */ 148 | - (nullable LCImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 149 | options:(LCWebImageOptions)options 150 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 151 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 152 | 153 | /** 154 | Creates a data task using the `sessionManager` instance for the specified URL request. 155 | 156 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 157 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 158 | task are executed in the order they were added. 159 | 160 | @param request The URL request. 161 | @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. 162 | @param options The options to control image operation. 163 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 164 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 165 | 166 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 167 | cache and the URL request cache policy allows the cache to be used. 168 | */ 169 | 170 | - (nullable LCImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 171 | withReceiptID:(nonnull NSUUID *)receiptID 172 | options:(LCWebImageOptions)options 173 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 174 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 175 | /** 176 | Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. 177 | 178 | If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. 179 | 180 | @param imageDownloadReceipt The image download receipt to cancel. 181 | */ 182 | - (void)cancelTaskForImageDownloadReceipt:(LCImageDownloadReceipt *)imageDownloadReceipt; 183 | 184 | @end 185 | 186 | NS_ASSUME_NONNULL_END 187 | -------------------------------------------------------------------------------- /LCWebImage/UIButton+LCWebImage.h: -------------------------------------------------------------------------------- 1 | // UIButton+LCWebImage.h 2 | // 3 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 4 | // 5 | // Created by 刘畅 on 2022/5/12. 6 | // Copyright © 2022 LiuChang. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "LCWebImageManager.h" 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | /** 15 | This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. 16 | 17 | @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. 18 | */ 19 | @interface UIButton (LCWebImage) 20 | 21 | ///------------------------------------ 22 | /// @name Accessing the Image Manager 23 | ///------------------------------------ 24 | 25 | /** 26 | Set the shared image manager used to download images. 27 | 28 | @param imageManager The shared image manager used to download images. 29 | */ 30 | + (void)lc_setSharedImageManager:(LCWebImageManager *)imageManager; 31 | 32 | /** 33 | The shared image manager used to download images. 34 | */ 35 | + (LCWebImageManager *)lc_sharedImageManager; 36 | 37 | ///-------------------- 38 | /// @name Setting Image 39 | ///-------------------- 40 | 41 | /** 42 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 43 | 44 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 45 | 46 | @param url The URL used for the image request. 47 | @param state The control state. 48 | */ 49 | - (void)lc_setImageWithURL:(NSURL *)url 50 | forState:(UIControlState)state; 51 | 52 | /** 53 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 54 | 55 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 56 | 57 | @param url The URL used for the image request. 58 | @param state The control state. 59 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 60 | */ 61 | - (void)lc_setImageWithURL:(NSURL *)url 62 | forState:(UIControlState)state 63 | placeholderImage:(nullable UIImage *)placeholderImage; 64 | 65 | /** 66 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 67 | 68 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 69 | 70 | @param url The URL used for the image request. 71 | @param state The control state. 72 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 73 | @param options The options to control image operation. 74 | */ 75 | - (void)lc_setImageWithURL:(NSURL *)url 76 | forState:(UIControlState)state 77 | placeholderImage:(nullable UIImage *)placeholderImage 78 | options:(LCWebImageOptions)options; 79 | /** 80 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 81 | 82 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 83 | 84 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. 85 | 86 | @param urlRequest The URL request used for the image request. 87 | @param state The control state. 88 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 89 | @param options The options to control image operation. 90 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 91 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 92 | */ 93 | - (void)lc_setImageWithURLRequest:(NSURLRequest *)urlRequest 94 | forState:(UIControlState)state 95 | placeholderImage:(nullable UIImage *)placeholderImage 96 | options:(LCWebImageOptions)options 97 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 98 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 99 | 100 | ///------------------------------- 101 | /// @name Setting Background Image 102 | ///------------------------------- 103 | 104 | /** 105 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. 106 | 107 | If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. 108 | 109 | @param url The URL used for the background image request. 110 | @param state The control state. 111 | */ 112 | - (void)lc_setBackgroundImageWithURL:(NSURL *)url 113 | forState:(UIControlState)state; 114 | /** 115 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 116 | 117 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 118 | 119 | @param url The URL used for the background image request. 120 | @param state The control state. 121 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 122 | */ 123 | - (void)lc_setBackgroundImageWithURL:(NSURL *)url 124 | forState:(UIControlState)state 125 | placeholderImage:(nullable UIImage *)placeholderImage; 126 | 127 | /** 128 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 129 | 130 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 131 | 132 | @param url The URL used for the background image request. 133 | @param state The control state. 134 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 135 | @param options The options to control image operation. 136 | */ 137 | - (void)lc_setBackgroundImageWithURL:(NSURL *)url 138 | forState:(UIControlState)state 139 | placeholderImage:(nullable UIImage *)placeholderImage 140 | options:(LCWebImageOptions)options; 141 | 142 | /** 143 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 144 | 145 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 146 | 147 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. 148 | 149 | @param urlRequest The URL request used for the image request. 150 | @param state The control state. 151 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 152 | @param options The options to control image operation. 153 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 154 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 155 | */ 156 | - (void)lc_setBackgroundImageWithURLRequest:(NSURLRequest *)urlRequest 157 | forState:(UIControlState)state 158 | placeholderImage:(nullable UIImage *)placeholderImage 159 | options:(LCWebImageOptions)options 160 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 161 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 162 | 163 | ///------------------------------ 164 | /// @name Canceling Image Loading 165 | ///------------------------------ 166 | 167 | /** 168 | Cancels any executing image task for the specified control state of the receiver, if one exists. 169 | 170 | @param state The control state. 171 | */ 172 | - (void)lc_cancelImageDownloadTaskForState:(UIControlState)state; 173 | 174 | /** 175 | Cancels any executing background image task for the specified control state of the receiver, if one exists. 176 | 177 | @param state The control state. 178 | */ 179 | - (void)lc_cancelBackgroundImageDownloadTaskForState:(UIControlState)state; 180 | 181 | @end 182 | 183 | NS_ASSUME_NONNULL_END 184 | -------------------------------------------------------------------------------- /LCWebImage/UIImage+LCDecoder.h: -------------------------------------------------------------------------------- 1 | // UIImage+LCDecoder.h 2 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 3 | // 4 | // Created by 刘畅 on 2022/5/23. 5 | // Copyright © 2022 LiuChang. All rights reserved. 6 | // 7 | 8 | #import 9 | 10 | NS_ASSUME_NONNULL_BEGIN 11 | 12 | @interface UIImage (LCDecoder) 13 | 14 | /** 15 | Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image 16 | @param image The image to be decoded 17 | @return The decoded image 18 | */ 19 | + (UIImage *)lc_decodedImageWithImage:(UIImage *)image; 20 | 21 | /** 22 | 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 `lc_decodedImageWithImage:`, never scale up. 23 | @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. 24 | 25 | @param image The image to be decoded and scaled down 26 | @param bytes The limit bytes size. Provide 0 to use the build-in limit. 27 | @return The decoded and probably scaled down image 28 | */ 29 | + (UIImage *)lc_decodedAndScaledDownImageWithImage:(UIImage *)image limitBytes:(NSUInteger)bytes; 30 | 31 | @end 32 | 33 | NS_ASSUME_NONNULL_END 34 | -------------------------------------------------------------------------------- /LCWebImage/UIImageView+LCWebImage.h: -------------------------------------------------------------------------------- 1 | // UIImageView+LCWebImage.h 2 | // 3 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 4 | // 5 | // Created by 刘畅 on 2022/5/12. 6 | // Copyright © 2022 LiuChang. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "LCWebImageManager.h" 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | /** 15 | This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. 16 | */ 17 | @interface UIImageView (LCWebImage) 18 | 19 | ///------------------------------------ 20 | /// @name Accessing the Image Downloader 21 | ///------------------------------------ 22 | 23 | /** 24 | Set the shared image manager used to download images. 25 | 26 | @param imageManager The shared image manager used to download images. 27 | */ 28 | + (void)lc_setSharedImageManager:(LCWebImageManager *)imageManager; 29 | 30 | /** 31 | The shared image manager used to download images. 32 | */ 33 | + (LCWebImageManager *)lc_sharedImageManager; 34 | 35 | ///-------------------- 36 | /// @name Setting Image 37 | ///-------------------- 38 | 39 | /** 40 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 41 | 42 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 43 | 44 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. 45 | 46 | @param url The URL used for the image request. 47 | */ 48 | - (void)lc_setImageWithURL:(NSURL *)url; 49 | 50 | /** 51 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 52 | 53 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 54 | 55 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. 56 | 57 | @param url The URL used for the image request. 58 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 59 | */ 60 | - (void)lc_setImageWithURL:(NSURL *)url 61 | placeholderImage:(nullable UIImage *)placeholderImage; 62 | 63 | /** 64 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 65 | 66 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 67 | 68 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. 69 | 70 | @param url The URL used for the image request. 71 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 72 | @param options The options to control image operation. 73 | */ 74 | - (void)lc_setImageWithURL:(NSURL *)url 75 | placeholderImage:(nullable UIImage *)placeholderImage 76 | options:(LCWebImageOptions)options; 77 | /** 78 | Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 79 | 80 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 81 | 82 | If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. 83 | 84 | @param urlRequest The URL request used for the image request. 85 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 86 | @param options The options to control image operation. 87 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 88 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 89 | */ 90 | - (void)lc_setImageWithURLRequest:(NSURLRequest *)urlRequest 91 | placeholderImage:(nullable UIImage *)placeholderImage 92 | options:(LCWebImageOptions)options 93 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 94 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 95 | 96 | /** 97 | Cancels any executing image operation for the receiver, if one exists. 98 | */ 99 | - (void)lc_cancelImageDownloadTask; 100 | 101 | @end 102 | 103 | NS_ASSUME_NONNULL_END 104 | -------------------------------------------------------------------------------- /LCWebImage/UIImageView+LCWebImage.m: -------------------------------------------------------------------------------- 1 | // UIImageView+LCWebImage.m 2 | // 3 | // LCWebImage (https://github.com/iLiuChang/LCWebImage) 4 | // 5 | // Created by 刘畅 on 2022/5/12. 6 | // Copyright © 2022 LiuChang. All rights reserved. 7 | // 8 | 9 | #import "UIImageView+LCWebImage.h" 10 | #import 11 | 12 | @interface UIImageView (_LCWebImage) 13 | @property (readwrite, nonatomic, strong, setter = lc_setActiveImageDownloadReceipt:) LCImageDownloadReceipt *lc_activeImageDownloadReceipt; 14 | @end 15 | 16 | @implementation UIImageView (_LCWebImage) 17 | 18 | - (LCImageDownloadReceipt *)lc_activeImageDownloadReceipt { 19 | return (LCImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(lc_activeImageDownloadReceipt)); 20 | } 21 | 22 | - (void)lc_setActiveImageDownloadReceipt:(LCImageDownloadReceipt *)imageDownloadReceipt { 23 | objc_setAssociatedObject(self, @selector(lc_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 24 | } 25 | 26 | @end 27 | 28 | #pragma mark - 29 | 30 | @implementation UIImageView (LCWebImage) 31 | 32 | + (LCWebImageManager *)lc_sharedImageManager { 33 | return objc_getAssociatedObject([UIImageView class], @selector(lc_sharedImageManager)) ?: [LCWebImageManager defaultInstance]; 34 | } 35 | 36 | + (void)lc_setSharedImageManager:(LCWebImageManager *)imageManager { 37 | objc_setAssociatedObject([UIImageView class], @selector(lc_sharedImageManager), imageManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 38 | } 39 | 40 | #pragma mark - 41 | 42 | - (void)lc_setImageWithURL:(NSURL *)url { 43 | [self lc_setImageWithURL:url placeholderImage:nil]; 44 | } 45 | 46 | - (void)lc_setImageWithURL:(NSURL *)url 47 | placeholderImage:(UIImage *)placeholderImage 48 | { 49 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 50 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 51 | [self lc_setImageWithURLRequest:request placeholderImage:placeholderImage options:0 success:nil failure:nil]; 52 | } 53 | 54 | - (void)lc_setImageWithURL:(NSURL *)url 55 | placeholderImage:(UIImage *)placeholderImage 56 | options:(LCWebImageOptions)options 57 | { 58 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 59 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 60 | [self lc_setImageWithURLRequest:request placeholderImage:placeholderImage options:options success:nil failure:nil]; 61 | } 62 | 63 | - (void)lc_setImageWithURLRequest:(NSURLRequest *)urlRequest 64 | placeholderImage:(UIImage *)placeholderImage 65 | options:(LCWebImageOptions)options 66 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 67 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure 68 | { 69 | if ([urlRequest URL] == nil) { 70 | self.image = placeholderImage; 71 | if (failure) { 72 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; 73 | failure(urlRequest, nil, error); 74 | } 75 | return; 76 | } 77 | 78 | if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) { 79 | return; 80 | } 81 | 82 | [self lc_cancelImageDownloadTask]; 83 | 84 | LCWebImageManager *downloader = [[self class] lc_sharedImageManager]; 85 | id imageCache = downloader.imageCache; 86 | 87 | //Use the image from the image cache if it exists 88 | UIImage *cachedImage = [imageCache memoryImageWithIdentifier:urlRequest.URL.absoluteString]; 89 | if (cachedImage) { 90 | if (success) { 91 | success(urlRequest, nil, cachedImage); 92 | } else { 93 | self.image = cachedImage; 94 | } 95 | [self clearActiveDownloadInformation]; 96 | } else if (!(options & LCWebImageOptionIgnoreDiskCache) && 97 | [imageCache containsDiskDataWithIdentifier:urlRequest.URL.absoluteString]) { 98 | NSUUID *downloadID = [NSUUID UUID]; 99 | __weak __typeof(self)weakSelf = self; 100 | LCImageDownloadReceipt *receipt = [downloader diskImageForURL:urlRequest.URL withReceiptID:downloadID completion:^(UIImage * _Nonnull image) { 101 | __strong __typeof(weakSelf)strongSelf = weakSelf; 102 | if ([strongSelf.lc_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 103 | if (success) { 104 | success(urlRequest, nil, image); 105 | } else { 106 | if (options & LCWebImageOptionNilImageUsePlaceHolder) { 107 | strongSelf.image = image?:placeholderImage; 108 | } else { 109 | strongSelf.image = image; 110 | } 111 | } 112 | [strongSelf clearActiveDownloadInformation]; 113 | } 114 | }]; 115 | self.lc_activeImageDownloadReceipt = receipt; 116 | } else { 117 | if (placeholderImage) { 118 | self.image = placeholderImage; 119 | } 120 | 121 | __weak __typeof(self)weakSelf = self; 122 | NSUUID *downloadID = [NSUUID UUID]; 123 | LCImageDownloadReceipt *receipt; 124 | receipt = [downloader 125 | downloadImageForURLRequest:urlRequest 126 | withReceiptID:downloadID 127 | options:options 128 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { 129 | __strong __typeof(weakSelf)strongSelf = weakSelf; 130 | if ([strongSelf.lc_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 131 | if (success) { 132 | success(request, response, responseObject); 133 | } else { 134 | if (options & LCWebImageOptionNilImageUsePlaceHolder) { 135 | strongSelf.image = responseObject?:placeholderImage; 136 | } else { 137 | strongSelf.image = responseObject; 138 | } 139 | } 140 | [strongSelf clearActiveDownloadInformation]; 141 | } 142 | 143 | } 144 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { 145 | __strong __typeof(weakSelf)strongSelf = weakSelf; 146 | if ([strongSelf.lc_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 147 | if (failure) { 148 | failure(request, response, error); 149 | } else { 150 | strongSelf.image = placeholderImage; 151 | } 152 | [strongSelf clearActiveDownloadInformation]; 153 | } 154 | }]; 155 | 156 | self.lc_activeImageDownloadReceipt = receipt; 157 | } 158 | } 159 | 160 | - (void)lc_cancelImageDownloadTask { 161 | if (self.lc_activeImageDownloadReceipt != nil) { 162 | [[self.class lc_sharedImageManager] cancelTaskForImageDownloadReceipt:self.lc_activeImageDownloadReceipt]; 163 | [self clearActiveDownloadInformation]; 164 | } 165 | } 166 | 167 | - (void)clearActiveDownloadInformation { 168 | self.lc_activeImageDownloadReceipt = nil; 169 | } 170 | 171 | - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { 172 | return [self.lc_activeImageDownloadReceipt.url.absoluteString isEqualToString:urlRequest.URL.absoluteString]; 173 | } 174 | 175 | @end 176 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 LiuChang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LCWebImage 2 | LCWebImage is an asynchronous image loading framework based on [AFNetworking](https://github.com/AFNetworking/AFNetworking), which supports memory and disk caching, and provides functions such as custom caching, custom image decoding, and custom network configuration. 3 | 4 | Animation playback is not supported by default. If you need to support animation, you can implement custom decoding (such as [YYImage](https://github.com/ibireme/YYImage)). 5 | 6 | ## Requirements 7 | 8 | - **iOS 9.0+** 9 | - **Xcode 11.0+** 10 | - **AFNetworking 4.0+** 11 | 12 | ## Usage 13 | 14 | ### Load image 15 | 16 | ```objective-c 17 | // UIImageView 18 | [imageView lc_setImageWithURL:[NSURL URLWithString:@"https://xxx"]]; 19 | 20 | // UIButton 21 | [button lc_setImageWithURL:[NSURL URLWithString:@"https://xxx"] forState:(UIControlStateNormal)]; 22 | ``` 23 | 24 | ### Custom decoding playback animation 25 | 26 | Use [YYImage](https://github.com/ibireme/YYImage) to implement custom decoding 27 | 28 | ```objective-c 29 | // custom 30 | [(LCAutoPurgingImageCache *)[LCWebImageManager defaultInstance].imageCache setCustomDecodedImage:^UIImage * _Nonnull(NSData * _Nonnull data, NSString * _Nonnull identifier) { 31 | return [[YYImage alloc] initWithData:data scale:UIScreen.mainScreen.scale]; 32 | }]; 33 | ``` 34 | 35 | Load image 36 | 37 | ```objective-c 38 | YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] init]; 39 | [imageView lc_setImageWithURL:[NSURL URLWithString:@"https://xxx"]]; 40 | ``` 41 | 42 | 43 | 44 | > Note: There is a display problem with YYImage above iOS 14. The source code of `YYAnimatedImageView` needs to be modified as follows: 45 | 46 | ```objective-c 47 | - (void)displayLayer:(CALayer *)layer { 48 | // modified code 49 | UIImage *currentFrame = _curFrame; 50 | if (currentFrame) { 51 | layer.contentsScale = currentFrame.scale; 52 | layer.contents = (__bridge id)currentFrame.CGImage; 53 | } else { 54 | // If we have no animation frames, call super implementation. iOS 14+ UIImageView use this delegate method for rendering. 55 | if ([UIImageView instancesRespondToSelector:@selector(displayLayer:)]) { 56 | [super displayLayer:layer]; 57 | } 58 | } 59 | 60 | // source code 61 | // if (_curFrame) { 62 | // layer.contents = (__bridge id)_curFrame.CGImage; 63 | // } 64 | } 65 | 66 | ``` 67 | 68 | ## Installation 69 | 70 | ### CocoaPods 71 | 72 | To integrate LCWebImage into your Xcode project using CocoaPods, specify it in your `Podfile`: 73 | 74 | ```ruby 75 | pod 'LCWebImage' 76 | ``` 77 | 78 | ### Manual 79 | 80 | 1. Download everything inside the LCWebImage folder; 81 | 2. Add (drag and drop) the source files in LCWebImage to your project; 82 | 3. Add `AFNetworking/NSURLSession` code. 83 | 84 | ## License 85 | 86 | LCWebImage is provided under the MIT license. See LICENSE file for details. 87 | 88 | --------------------------------------------------------------------------------