├── .gitignore ├── LICENSE ├── README.md └── SDWebImage-translateTo-Chinese ├── SDWebImage-translateTo-Chinese.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── Macx.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── Macx.xcuserdatad │ └── xcschemes │ ├── SDWebImage-translateTo-Chinese.xcscheme │ └── xcschememanagement.plist ├── SDWebImage-translateTo-Chinese └── SDWebImage │ ├── Cache(缓存) │ ├── SDImageCache.h │ └── SDImageCache.m │ ├── Categories(分类) │ ├── MKAnnotationView+WebCache.h │ ├── MKAnnotationView+WebCache.m │ ├── NSData+ImageContentType.h │ ├── NSData+ImageContentType.m │ ├── UIButton+WebCache.h │ ├── UIButton+WebCache.m │ ├── UIImage+GIF.h │ ├── UIImage+GIF.m │ ├── UIImage+MultiFormat.h │ ├── UIImage+MultiFormat.m │ ├── UIImage+WebP.h │ ├── UIImage+WebP.m │ ├── UIImageView+HighlightedWebCache.h │ ├── UIImageView+HighlightedWebCache.m │ ├── UIImageView+WebCache.h │ ├── UIImageView+WebCache.m │ ├── UIView+WebCacheOperation.h │ └── UIView+WebCacheOperation.m │ ├── Downloader(下载) │ ├── SDWebImageDownloader.h │ ├── SDWebImageDownloader.m │ ├── SDWebImageDownloaderOperation.h │ └── SDWebImageDownloaderOperation.m │ ├── SDWebImageCompat.h │ ├── SDWebImageCompat.m │ ├── SDWebImageOperation.h │ └── Utils(工具) │ ├── SDWebImageDecoder.h │ ├── SDWebImageDecoder.m │ ├── SDWebImageManager.h │ ├── SDWebImageManager.m │ ├── SDWebImagePrefetcher.h │ └── SDWebImagePrefetcher.m ├── SDWebImage-translateTo-ChineseTests ├── Info.plist └── SDWebImage_translateTo_ChineseTests.m └── SDWebImage-translateTo-ChineseUITests ├── Info.plist └── SDWebImage_translateTo_ChineseUITests.m /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | build/ 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | xcuserdata 13 | *.xccheckout 14 | *.moved-aside 15 | DerivedData 16 | *.hmap 17 | *.ipa 18 | *.xcuserstate 19 | 20 | # CocoaPods 21 | # 22 | # We recommend against adding the Pods directory to your .gitignore. However 23 | # you should judge for yourself, the pros and cons are mentioned at: 24 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 25 | # 26 | #Pods/ 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SDWebImage-translateTo-Chinese 2 | SDWebImage 注释翻译 3 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese.xcodeproj/project.xcworkspace/xcuserdata/Macx.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CYXiang/SDWebImage-translateTo-Chinese/e2ce6f0c7203136f2f0a1b76e0f085a8524ad9c3/SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese.xcodeproj/project.xcworkspace/xcuserdata/Macx.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese.xcodeproj/xcuserdata/Macx.xcuserdatad/xcschemes/SDWebImage-translateTo-Chinese.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 43 | 49 | 50 | 51 | 52 | 53 | 59 | 60 | 61 | 62 | 63 | 64 | 74 | 76 | 82 | 83 | 84 | 85 | 86 | 87 | 93 | 95 | 101 | 102 | 103 | 104 | 106 | 107 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese.xcodeproj/xcuserdata/Macx.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | SDWebImage-translateTo-Chinese.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 8F845BE21BC55A8A0074D56E 16 | 17 | primary 18 | 19 | 20 | 8F845BFB1BC55A8A0074D56E 21 | 22 | primary 23 | 24 | 25 | 8F845C061BC55A8A0074D56E 26 | 27 | primary 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Cache(缓存)/SDImageCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | typedef NS_ENUM(NSInteger, SDImageCacheType) { 13 | /** 14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web. 15 | * 不使用 SDWebImage 缓存,从网络下载 16 | */ 17 | SDImageCacheTypeNone, 18 | /** 19 | * The image was obtained from the disk cache. 20 | * 磁盘缓存图像 21 | */ 22 | SDImageCacheTypeDisk, 23 | /** 24 | * The image was obtained from the memory cache. 25 | * 内存缓存图像 26 | */ 27 | SDImageCacheTypeMemory 28 | }; 29 | 30 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); 31 | 32 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); 33 | 34 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); 35 | 36 | /** 37 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed 38 | * asynchronous so it doesn’t add unnecessary latency to the UI. 39 | *
SDImageCache 维护一个内存缓存以及一个"可选"的磁盘缓存。磁盘缓存的写入操作是异步执行,因此不会造成 UI 的延迟 40 | */ 41 | @interface SDImageCache : NSObject 42 | 43 | /** 44 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 45 | *
最大内存图像缓存值,以像素值为单位,默认数值为0 46 | */ 47 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 48 | 49 | /** 50 | * The maximum length of time to keep an image in the cache, in seconds 51 | *
缓存图像最长时间,以秒为单位,默认一周 52 | */ 53 | @property (assign, nonatomic) NSInteger maxCacheAge; 54 | 55 | /** 56 | * The maximum size of the cache, in bytes. 57 | *
缓存图像总大小,以字节为单位,默认数值为0 58 | */ 59 | @property (assign, nonatomic) NSUInteger maxCacheSize; 60 | 61 | /** 62 | * Returns global shared cache instance 63 | *
返回全局的缓存实例 64 | * 65 | * @return SDImageCache global instance 66 | *
SDImageCache 全局实例 67 | */ 68 | + (SDImageCache *)sharedImageCache; 69 | 70 | /** 71 | * Init a new cache store with a specific namespace 72 | *
使用指定的命名空间实例化一个新的缓存存储 73 | * 74 | * @param ns The namespace to use for this cache store 75 | *
缓存存储使用的命名空间 76 | */ 77 | - (id)initWithNamespace:(NSString *)ns; 78 | 79 | /** 80 | * Add a read-only cache path to search for images pre-cached by SDImageCache 81 | * Useful if you want to bundle pre-loaded images with your app 82 | *
如果希望在 bundle 中存储预加载的图像,可以添加一个只读的缓存路径,让 SDImageCache 从 Bundle 中搜索预先缓存的图像 83 | * 84 | * @param path The path to use for this read-only cache path 85 | *
只读缓存路径(mainBundle中的全路径) 86 | */ 87 | - (void)addReadOnlyCachePath:(NSString *)path; 88 | 89 | /** 90 | * Store an image into memory and disk cache at the given key. 91 | *
使用指定的键将图像保存到内存和磁盘缓存 92 | * 93 | * @param image The image to store 94 | *
要保存的图像 95 | * @param key The unique image cache key, usually it's image absolute URL 96 | *
唯一的图像缓存键,通常是图像的完整 URL 97 | */ 98 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 99 | 100 | /** 101 | * Store an image into memory and optionally disk cache at the given key. 102 | *
使用指定的键将图像保存到内存和可选的磁盘缓存 103 | * 104 | * @param image The image to store 105 | *
要保存的图像 106 | * @param key The unique image cache key, usually it's image absolute URL 107 | *
唯一的图像缓存键,通常是图像的完整 URL 108 | * @param toDisk Store the image to disk cache if YES 109 | *
如果是 YES,则将图像缓存到磁盘 110 | */ 111 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 112 | 113 | /** 114 | * Store an image into memory and optionally disk cache at the given key. 115 | *
使用指定的键将图像保存到内存和可选的磁盘缓存 116 | * 117 | * @param image The image to store 118 | *
要保存的图像 119 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 120 | *
是否直接使用 imageData,还是从 UIImage 重新构造数据 121 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 122 | * instead of converting the given image object into a storable/compressed image format in order 123 | * to save quality and CPU 124 | *
从服务器返回图像的二进制数据,表示直接保存到磁盘,而不是将给定的图像对象转换成一个可存储/可压缩的图像格式,从而保留图片质量并降低 CPU 开销 125 | * @param key The unique image cache key, usually it's image absolute URL 126 | *
唯一的图像缓存键,通常是图像的完整 URL 127 | * @param toDisk Store the image to disk cache if YES 128 | *
如果是 YES,则将图像缓存到磁盘 129 | */ 130 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 131 | 132 | /** 133 | * Query the disk cache asynchronously. 134 | *
异步查询磁盘缓存 135 | * 136 | * @param key The unique key used to store the wanted image 137 | *
保存图像的唯一键 138 | */ 139 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 140 | 141 | /** 142 | * Query the memory cache synchronously. 143 | *
同步查询内存缓存 144 | * 145 | * @param key The unique key used to store the wanted image 146 | */ 147 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 148 | 149 | /** 150 | * Query the disk cache synchronously after checking the memory cache. 151 | *
查询内存缓存之后同步查询磁盘缓存 152 | * 153 | * @param key The unique key used to store the wanted image 154 | */ 155 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 156 | 157 | /** 158 | * Remove the image from memory and disk cache synchronously 159 | *
同步从内存和磁盘缓存删除图像 160 | * 161 | * @param key The unique image cache key 162 | */ 163 | - (void)removeImageForKey:(NSString *)key; 164 | 165 | 166 | /** 167 | * Remove the image from memory and disk cache synchronously 168 | *
同步从内存和磁盘缓存删除图像 169 | * 170 | * @param key The unique image cache key 171 | * @param completion An block that should be executed after the image has been removed (optional) 172 | */ 173 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 174 | 175 | /** 176 | * Remove the image from memory and optionally disk cache synchronously 177 | *
同步从内存和可选磁盘缓存删除图像 178 | * 179 | * @param key The unique image cache key 180 | * @param fromDisk Also remove cache entry from disk if YES 181 | * 如果是 YES,则从磁盘删除缓存 182 | */ 183 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 184 | 185 | /** 186 | * Remove the image from memory and optionally disk cache synchronously 187 | *
同步从内存和可选磁盘缓存删除图像 188 | * 189 | * @param key The unique image cache key 190 | * @param fromDisk Also remove cache entry from disk if YES 191 | * @param completion An block that should be executed after the image has been removed (optional) 192 | * 完成删除之后的块代码回调 193 | */ 194 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 195 | 196 | /** 197 | * Clear all memory cached images 198 | *
删除所有内存缓存的图像 199 | */ 200 | - (void)clearMemory; 201 | 202 | /** 203 | * Clear all disk cached images. Non-blocking method - returns immediately. 204 | *
删除所有磁盘缓存的图像。 205 | * 206 | * @param completion An block that should be executed after cache expiration completes (optional) 207 | * 删除操作后的块代码回调(可选) 208 | */ 209 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 210 | 211 | /** 212 | * Clear all disk cached images 213 | *
删除所有磁盘缓存的图像 214 | * 215 | * @see clearDiskOnCompletion: 216 | */ 217 | - (void)clearDisk; 218 | 219 | /** 220 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 221 | *
从磁盘中删除所有过期的缓存图像。 222 | * 223 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 224 | */ 225 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 226 | 227 | /** 228 | * Remove all expired cached image from disk 229 | *
从磁盘中删除所有过期的缓存图像。 230 | * @see cleanDiskWithCompletionBlock: 231 | */ 232 | - (void)cleanDisk; 233 | 234 | /** 235 | * Get the size used by the disk cache 236 | *
获得磁盘缓存占用空间 237 | */ 238 | - (NSUInteger)getSize; 239 | 240 | /** 241 | * Get the number of images in the disk cache 242 | *
获得缓存图像的个数 243 | */ 244 | - (NSUInteger)getDiskCount; 245 | 246 | /** 247 | * Asynchronously calculate the disk cache's size. 248 | *
异步计算磁盘缓存的大小 249 | */ 250 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 251 | 252 | /** 253 | * Async check if image exists in disk cache already (does not load the image) 254 | *
异步检查图像是否已经在磁盘缓存中存在(不加载图像) 255 | * 256 | * @param key the key describing the url 257 | * @param completionBlock the block to be executed when the check is done. 258 | * @note the completion block will be always executed on the main queue 259 | */ 260 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 261 | 262 | /** 263 | * Check if image exists in disk cache already (does not load the image) 264 | *
异步检查图像是否已经在磁盘缓存中存在(不加载图像) 265 | * 266 | * @param key the key describing the url 267 | * 268 | * @return YES if an image exists for the given key 269 | */ 270 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 271 | 272 | /** 273 | * Get the cache path for a certain key (needs the cache path root folder) 274 | *
获得指定 key 对应的缓存路径(需要指定缓存路径的根目录) 275 | * 276 | * @param key the key (can be obtained from url using cacheKeyForURL) 277 | * @param path the cach path root folder 278 | * 279 | * @return the cache path 280 | */ 281 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 282 | 283 | /** 284 | * Get the default cache path for a certain key 285 | *
获得指定 key 的默认缓存路径 286 | * 287 | * @param key the key (can be obtained from url using cacheKeyForURL) 288 | * 289 | * @return the default cache path 290 | */ 291 | - (NSString *)defaultCachePathForKey:(NSString *)key; 292 | 293 | @end 294 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Cache(缓存)/SDImageCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDImageCache.h" 10 | #import "SDWebImageDecoder.h" 11 | #import "UIImage+MultiFormat.h" 12 | #import 13 | 14 | // 最大缓存时间 一周 15 | static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week 16 | // PNG signature bytes and data (below) 17 | // PNG 签名字节和数据(PNG文件开始的8个字节是固定的) 18 | static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; 19 | static NSData *kPNGSignatureData = nil; 20 | 21 | BOOL ImageDataHasPNGPreffix(NSData *data); 22 | 23 | BOOL ImageDataHasPNGPreffix(NSData *data) { 24 | NSUInteger pngSignatureLength = [kPNGSignatureData length]; 25 | if ([data length] >= pngSignatureLength) { 26 | if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { 27 | return YES; 28 | } 29 | } 30 | 31 | return NO; 32 | } 33 | 34 | @interface SDImageCache () 35 | 36 | @property (strong, nonatomic) NSCache *memCache; 37 | @property (strong, nonatomic) NSString *diskCachePath; 38 | @property (strong, nonatomic) NSMutableArray *customPaths; 39 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; 40 | 41 | @end 42 | 43 | 44 | @implementation SDImageCache { 45 | NSFileManager *_fileManager; 46 | } 47 | 48 | + (SDImageCache *)sharedImageCache { 49 | static dispatch_once_t once; 50 | static id instance; 51 | dispatch_once(&once, ^{ 52 | instance = [self new]; 53 | }); 54 | return instance; 55 | } 56 | 57 | - (id)init { 58 | return [self initWithNamespace:@"default"]; 59 | } 60 | 61 | - (id)initWithNamespace:(NSString *)ns { 62 | if ((self = [super init])) { 63 | NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; 64 | 65 | // initialise PNG signature data 66 | kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; 67 | 68 | // Create IO serial queue 69 | // 磁盘读写队列,串行队列 70 | _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); 71 | 72 | // Init default values 73 | // 初始化默认数值,最大缓存时间一周 74 | _maxCacheAge = kDefaultCacheMaxCacheAge; 75 | 76 | // Init the memory cache 77 | // 初始化内存缓存 NSCache 78 | _memCache = [[NSCache alloc] init]; 79 | _memCache.name = fullNamespace; 80 | 81 | // Init the disk cache 82 | // 初始化磁盘缓存(使用完整的命名空间名作为缓存文件目录名) 83 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 84 | _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace]; 85 | 86 | dispatch_sync(_ioQueue, ^{ 87 | _fileManager = [NSFileManager new]; 88 | }); 89 | 90 | #if TARGET_OS_IPHONE 91 | // Subscribe to app events 92 | // 监听应用程序事件 93 | // -接收到内存警告通知-清理内存操作 - clearMemory 94 | [[NSNotificationCenter defaultCenter] addObserver:self 95 | selector:@selector(clearMemory) 96 | name:UIApplicationDidReceiveMemoryWarningNotification 97 | object:nil]; 98 | 99 | // -应用程序将要终止通知-执行清理磁盘操作 - cleanDisk 100 | [[NSNotificationCenter defaultCenter] addObserver:self 101 | selector:@selector(cleanDisk) 102 | name:UIApplicationWillTerminateNotification 103 | object:nil]; 104 | 105 | // - 进入后台通知 - 后台清理磁盘 - backgroundCleanDisk 106 | [[NSNotificationCenter defaultCenter] addObserver:self 107 | selector:@selector(backgroundCleanDisk) 108 | name:UIApplicationDidEnterBackgroundNotification 109 | object:nil]; 110 | #endif 111 | } 112 | 113 | return self; 114 | } 115 | 116 | - (void)dealloc { 117 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 118 | SDDispatchQueueRelease(_ioQueue); 119 | } 120 | 121 | - (void)addReadOnlyCachePath:(NSString *)path { 122 | if (!self.customPaths) { 123 | self.customPaths = [NSMutableArray new]; 124 | } 125 | 126 | if (![self.customPaths containsObject:path]) { 127 | [self.customPaths addObject:path]; 128 | } 129 | } 130 | 131 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { 132 | NSString *filename = [self cachedFileNameForKey:key]; 133 | return [path stringByAppendingPathComponent:filename]; 134 | } 135 | 136 | - (NSString *)defaultCachePathForKey:(NSString *)key { 137 | return [self cachePathForKey:key inPath:self.diskCachePath]; 138 | } 139 | 140 | #pragma mark SDImageCache (private) 141 | 142 | - (NSString *)cachedFileNameForKey:(NSString *)key { 143 | const char *str = [key UTF8String]; 144 | if (str == NULL) { 145 | str = ""; 146 | } 147 | unsigned char r[CC_MD5_DIGEST_LENGTH]; 148 | CC_MD5(str, (CC_LONG)strlen(str), r); 149 | NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 150 | r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; 151 | 152 | return filename; 153 | } 154 | 155 | #pragma mark ImageCache 156 | 157 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { 158 | if (!image || !key) { 159 | return; 160 | } 161 | 162 | [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale * image.scale]; 163 | 164 | if (toDisk) { 165 | dispatch_async(self.ioQueue, ^{ 166 | NSData *data = imageData; 167 | 168 | if (image && (recalculate || !data)) { 169 | #if TARGET_OS_IPHONE 170 | // We need to determine if the image is a PNG or a JPEG 171 | // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) 172 | // The first eight bytes of a PNG file always contain the following (decimal) values: 173 | // 137 80 78 71 13 10 26 10 174 | 175 | // We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly), 176 | // we will consider it PNG to avoid loosing the transparency 177 | BOOL imageIsPng = YES; 178 | 179 | // But if we have an image data, we will look at the preffix 180 | if ([imageData length] >= [kPNGSignatureData length]) { 181 | imageIsPng = ImageDataHasPNGPreffix(imageData); 182 | } 183 | 184 | if (imageIsPng) { 185 | data = UIImagePNGRepresentation(image); 186 | } 187 | else { 188 | data = UIImageJPEGRepresentation(image, (CGFloat)1.0); 189 | } 190 | #else 191 | data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; 192 | #endif 193 | } 194 | 195 | if (data) { 196 | if (![_fileManager fileExistsAtPath:_diskCachePath]) { 197 | [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; 198 | } 199 | 200 | [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; 201 | } 202 | }); 203 | } 204 | } 205 | 206 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key { 207 | [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; 208 | } 209 | 210 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { 211 | [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; 212 | } 213 | 214 | - (BOOL)diskImageExistsWithKey:(NSString *)key { 215 | BOOL exists = NO; 216 | 217 | // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance 218 | // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely. 219 | // 共享的 NSFileManager 对象可以保证在多线程运行时是安全的 220 | // 检查文件是否存在 221 | exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]]; 222 | 223 | return exists; 224 | } 225 | 226 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 227 | dispatch_async(_ioQueue, ^{ 228 | BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; 229 | if (completionBlock) { 230 | dispatch_async(dispatch_get_main_queue(), ^{ 231 | completionBlock(exists); 232 | }); 233 | } 234 | }); 235 | } 236 | 237 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { 238 | return [self.memCache objectForKey:key]; 239 | } 240 | 241 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key { 242 | // First check the in-memory cache... 243 | UIImage *image = [self imageFromMemoryCacheForKey:key]; 244 | if (image) { 245 | return image; 246 | } 247 | 248 | // Second check the disk cache... 249 | UIImage *diskImage = [self diskImageForKey:key]; 250 | if (diskImage) { 251 | CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale * diskImage.scale; 252 | [self.memCache setObject:diskImage forKey:key cost:cost]; 253 | } 254 | 255 | return diskImage; 256 | } 257 | 258 | - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { 259 | NSString *defaultPath = [self defaultCachePathForKey:key]; 260 | NSData *data = [NSData dataWithContentsOfFile:defaultPath]; 261 | if (data) { 262 | return data; 263 | } 264 | 265 | for (NSString *path in self.customPaths) { 266 | NSString *filePath = [self cachePathForKey:key inPath:path]; 267 | NSData *imageData = [NSData dataWithContentsOfFile:filePath]; 268 | if (imageData) { 269 | return imageData; 270 | } 271 | } 272 | 273 | return nil; 274 | } 275 | 276 | - (UIImage *)diskImageForKey:(NSString *)key { 277 | NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; 278 | if (data) { 279 | UIImage *image = [UIImage sd_imageWithData:data]; 280 | image = [self scaledImageForKey:key image:image]; 281 | image = [UIImage decodedImageWithImage:image]; 282 | return image; 283 | } 284 | else { 285 | return nil; 286 | } 287 | } 288 | 289 | - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { 290 | return SDScaledImageForKey(key, image); 291 | } 292 | 293 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { 294 | if (!doneBlock) { 295 | return nil; 296 | } 297 | 298 | if (!key) { 299 | doneBlock(nil, SDImageCacheTypeNone); 300 | return nil; 301 | } 302 | 303 | // First check the in-memory cache... 304 | UIImage *image = [self imageFromMemoryCacheForKey:key]; 305 | if (image) { 306 | doneBlock(image, SDImageCacheTypeMemory); 307 | return nil; 308 | } 309 | 310 | NSOperation *operation = [NSOperation new]; 311 | dispatch_async(self.ioQueue, ^{ 312 | if (operation.isCancelled) { 313 | return; 314 | } 315 | 316 | @autoreleasepool { 317 | UIImage *diskImage = [self diskImageForKey:key]; 318 | if (diskImage) { 319 | CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale * diskImage.scale; 320 | [self.memCache setObject:diskImage forKey:key cost:cost]; 321 | } 322 | 323 | dispatch_async(dispatch_get_main_queue(), ^{ 324 | doneBlock(diskImage, SDImageCacheTypeDisk); 325 | }); 326 | } 327 | }); 328 | 329 | return operation; 330 | } 331 | 332 | - (void)removeImageForKey:(NSString *)key { 333 | [self removeImageForKey:key withCompletion:nil]; 334 | } 335 | 336 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion { 337 | [self removeImageForKey:key fromDisk:YES withCompletion:completion]; 338 | } 339 | 340 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { 341 | [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil]; 342 | } 343 | 344 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion { 345 | 346 | if (key == nil) { 347 | return; 348 | } 349 | 350 | [self.memCache removeObjectForKey:key]; 351 | 352 | if (fromDisk) { 353 | dispatch_async(self.ioQueue, ^{ 354 | [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; 355 | 356 | if (completion) { 357 | dispatch_async(dispatch_get_main_queue(), ^{ 358 | completion(); 359 | }); 360 | } 361 | }); 362 | } else if (completion){ 363 | completion(); 364 | } 365 | 366 | } 367 | 368 | - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { 369 | self.memCache.totalCostLimit = maxMemoryCost; 370 | } 371 | 372 | - (NSUInteger)maxMemoryCost { 373 | return self.memCache.totalCostLimit; 374 | } 375 | 376 | - (void)clearMemory { 377 | [self.memCache removeAllObjects]; 378 | } 379 | 380 | - (void)clearDisk { 381 | [self clearDiskOnCompletion:nil]; 382 | } 383 | 384 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion 385 | { 386 | dispatch_async(self.ioQueue, ^{ 387 | // 删除缓存路径 388 | [_fileManager removeItemAtPath:self.diskCachePath error:nil]; 389 | // 再次创建缓存路径 390 | [_fileManager createDirectoryAtPath:self.diskCachePath 391 | withIntermediateDirectories:YES 392 | attributes:nil 393 | error:NULL]; 394 | 395 | if (completion) { 396 | dispatch_async(dispatch_get_main_queue(), ^{ 397 | completion(); 398 | }); 399 | } 400 | }); 401 | } 402 | 403 | - (void)cleanDisk { 404 | [self cleanDiskWithCompletionBlock:nil]; 405 | } 406 | 407 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock { 408 | dispatch_async(self.ioQueue, ^{ 409 | NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; 410 | NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; 411 | 412 | // This enumerator prefetches useful properties for our cache files. 413 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL 414 | includingPropertiesForKeys:resourceKeys 415 | options:NSDirectoryEnumerationSkipsHiddenFiles 416 | errorHandler:NULL]; 417 | 418 | // 计算过期日期 419 | NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; 420 | NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; 421 | NSUInteger currentCacheSize = 0; 422 | 423 | // Enumerate all of the files in the cache directory. This loop has two purposes: 424 | // 遍历缓存路径中的所有文件,此循环要实现两个目的 425 | // 426 | // 1. Removing files that are older than the expiration date. 427 | // 删除早于过期日期的文件 428 | // 2. Storing file attributes for the size-based cleanup pass. 429 | // 保存文件属性以计算磁盘缓存占用空间 430 | // 431 | NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; 432 | for (NSURL *fileURL in fileEnumerator) { 433 | NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; 434 | 435 | // Skip directories. 跳过目录 436 | if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { 437 | continue; 438 | } 439 | 440 | // Remove files that are older than the expiration date; 记录要删除的过期文件 441 | NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; 442 | if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { 443 | [urlsToDelete addObject:fileURL]; 444 | continue; 445 | } 446 | 447 | // Store a reference to this file and account for its total size. 448 | // 保存文件引用,以计算总大小 449 | NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; 450 | currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; 451 | [cacheFiles setObject:resourceValues forKey:fileURL]; 452 | } 453 | 454 | // 删除过期的文件 455 | for (NSURL *fileURL in urlsToDelete) { 456 | [_fileManager removeItemAtURL:fileURL error:nil]; 457 | } 458 | 459 | // If our remaining disk cache exceeds a configured maximum size, perform a second 460 | // size-based cleanup pass. We delete the oldest files first. 461 | // 如果剩余磁盘缓存空间超出最大限额,再次执行清理操作,删除最早的文件 462 | if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { 463 | // Target half of our maximum cache size for this cleanup pass. 464 | const NSUInteger desiredCacheSize = self.maxCacheSize / 2; 465 | 466 | // Sort the remaining cache files by their last modification time (oldest first). 467 | NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent 468 | usingComparator:^NSComparisonResult(id obj1, id obj2) { 469 | return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; 470 | }]; 471 | 472 | // Delete files until we fall below our desired cache size. 473 | // 循环依次删除文件,直到低于期望的缓存限额 474 | for (NSURL *fileURL in sortedFiles) { 475 | if ([_fileManager removeItemAtURL:fileURL error:nil]) { 476 | NSDictionary *resourceValues = cacheFiles[fileURL]; 477 | NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; 478 | currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; 479 | 480 | if (currentCacheSize < desiredCacheSize) { 481 | break; 482 | } 483 | } 484 | } 485 | } 486 | if (completionBlock) { 487 | dispatch_async(dispatch_get_main_queue(), ^{ 488 | completionBlock(); 489 | }); 490 | } 491 | }); 492 | } 493 | 494 | - (void)backgroundCleanDisk { 495 | UIApplication *application = [UIApplication sharedApplication]; 496 | __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 497 | // Clean up any unfinished task business by marking where you 498 | // stopped or ending the task outright. 499 | [application endBackgroundTask:bgTask]; 500 | bgTask = UIBackgroundTaskInvalid; 501 | }]; 502 | 503 | // Start the long-running task and return immediately. 504 | [self cleanDiskWithCompletionBlock:^{ 505 | [application endBackgroundTask:bgTask]; 506 | bgTask = UIBackgroundTaskInvalid; 507 | }]; 508 | } 509 | 510 | - (NSUInteger)getSize { 511 | __block NSUInteger size = 0; 512 | dispatch_sync(self.ioQueue, ^{ 513 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; 514 | for (NSString *fileName in fileEnumerator) { 515 | NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; 516 | NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; 517 | size += [attrs fileSize]; 518 | } 519 | }); 520 | return size; 521 | } 522 | 523 | - (NSUInteger)getDiskCount { 524 | __block NSUInteger count = 0; 525 | dispatch_sync(self.ioQueue, ^{ 526 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; 527 | count = [[fileEnumerator allObjects] count]; 528 | }); 529 | return count; 530 | } 531 | 532 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock { 533 | NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; 534 | 535 | dispatch_async(self.ioQueue, ^{ 536 | NSUInteger fileCount = 0; 537 | NSUInteger totalSize = 0; 538 | 539 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL 540 | includingPropertiesForKeys:@[NSFileSize] 541 | options:NSDirectoryEnumerationSkipsHiddenFiles 542 | errorHandler:NULL]; 543 | 544 | for (NSURL *fileURL in fileEnumerator) { 545 | NSNumber *fileSize; 546 | [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; 547 | totalSize += [fileSize unsignedIntegerValue]; 548 | fileCount += 1; 549 | } 550 | 551 | if (completionBlock) { 552 | dispatch_async(dispatch_get_main_queue(), ^{ 553 | completionBlock(fileCount, totalSize); 554 | }); 555 | } 556 | }); 557 | } 558 | 559 | @end 560 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/MKAnnotationView+WebCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // MKAnnotationView+WebCache.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 14/03/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "MapKit/MapKit.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with MKAnnotationView. 14 | */ 15 | @interface MKAnnotationView (WebCache) 16 | 17 | /** 18 | * Get the current image URL. 19 | * 20 | * Note that because of the limitations of categories this property can get out of sync 21 | * if you use sd_setImage: directly. 22 | */ 23 | - (NSURL *)sd_imageURL; 24 | 25 | /** 26 | * Set the imageView `image` with an `url`. 27 | * 28 | * The download is asynchronous and cached. 29 | * 30 | * @param url The url for the image. 31 | */ 32 | - (void)sd_setImageWithURL:(NSURL *)url; 33 | 34 | /** 35 | * Set the imageView `image` with an `url` and a placeholder. 36 | * 37 | * The download is asynchronous and cached. 38 | * 39 | * @param url The url for the image. 40 | * @param placeholder The image to be set initially, until the image request finishes. 41 | * @see sd_setImageWithURL:placeholderImage:options: 42 | */ 43 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 44 | 45 | /** 46 | * Set the imageView `image` with an `url`, placeholder and custom options. 47 | * 48 | * The download is asynchronous and cached. 49 | * 50 | * @param url The url for the image. 51 | * @param placeholder The image to be set initially, until the image request finishes. 52 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 53 | */ 54 | 55 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 56 | 57 | /** 58 | * Set the imageView `image` with an `url`. 59 | * 60 | * The download is asynchronous and cached. 61 | * 62 | * @param url The url for the image. 63 | * @param completedBlock A block called when operation has been completed. This block has no return value 64 | * and takes the requested UIImage as first parameter. In case of error the image parameter 65 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 66 | * indicating if the image was retrived from the local cache or from the network. 67 | * The fourth parameter is the original image url. 68 | */ 69 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 70 | 71 | /** 72 | * Set the imageView `image` with an `url`, placeholder. 73 | * 74 | * The download is asynchronous and cached. 75 | * 76 | * @param url The url for the image. 77 | * @param placeholder The image to be set initially, until the image request finishes. 78 | * @param completedBlock A block called when operation has been completed. This block has no return value 79 | * and takes the requested UIImage as first parameter. In case of error the image parameter 80 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 81 | * indicating if the image was retrived from the local cache or from the network. 82 | * The fourth parameter is the original image url. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`, placeholder and custom options. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param placeholder The image to be set initially, until the image request finishes. 93 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 94 | * @param completedBlock A block called when operation has been completed. This block has no return value 95 | * and takes the requested UIImage as first parameter. In case of error the image parameter 96 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 97 | * indicating if the image was retrived from the local cache or from the network. 98 | * The fourth parameter is the original image url. 99 | */ 100 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 101 | 102 | /** 103 | * Cancel the current download 104 | */ 105 | - (void)sd_cancelCurrentImageLoad; 106 | 107 | @end 108 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/MKAnnotationView+WebCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // MKAnnotationView+WebCache.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 14/03/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "MKAnnotationView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | 15 | @implementation MKAnnotationView (WebCache) 16 | 17 | - (NSURL *)sd_imageURL { 18 | return objc_getAssociatedObject(self, &imageURLKey); 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url { 22 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 30 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options completed:nil]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | 44 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 45 | self.image = placeholder; 46 | 47 | if (url) { 48 | __weak MKAnnotationView *wself = self; 49 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 50 | if (!wself) return; 51 | dispatch_main_sync_safe(^{ 52 | __strong MKAnnotationView *sself = wself; 53 | if (!sself) return; 54 | if (image) { 55 | sself.image = image; 56 | } 57 | if (completedBlock && finished) { 58 | completedBlock(image, error, cacheType, url); 59 | } 60 | }); 61 | }]; 62 | [self sd_setImageLoadOperation:operation forKey:@"MKAnnotationViewImage"]; 63 | } else { 64 | dispatch_main_async_safe(^{ 65 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 66 | if (completedBlock) { 67 | completedBlock(nil, error, SDImageCacheTypeNone, url); 68 | } 69 | }); 70 | } 71 | } 72 | 73 | - (void)sd_cancelCurrentImageLoad { 74 | [self sd_cancelImageLoadOperationWithKey:@"MKAnnotationViewImage"]; 75 | } 76 | 77 | @end 78 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/NSData+ImageContentType.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import 7 | 8 | @interface NSData (ImageContentType) 9 | 10 | /** 11 | * Compute the content type for an image data 12 | * 13 | * @param data the input data 14 | * 15 | * @return the content type as string (i.e. image/jpeg, image/gif) 16 | */ 17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/NSData+ImageContentType.m: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import "NSData+ImageContentType.h" 7 | 8 | 9 | @implementation NSData (ImageContentType) 10 | 11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data { 12 | uint8_t c; 13 | [data getBytes:&c length:1]; 14 | switch (c) { 15 | case 0xFF: 16 | return @"image/jpeg"; 17 | case 0x89: 18 | return @"image/png"; 19 | case 0x47: 20 | return @"image/gif"; 21 | case 0x49: 22 | case 0x4D: 23 | return @"image/tiff"; 24 | case 0x52: 25 | // R as RIFF for WEBP 26 | if ([data length] < 12) { 27 | return nil; 28 | } 29 | 30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; 31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { 32 | return @"image/webp"; 33 | } 34 | 35 | return nil; 36 | } 37 | return nil; 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIButton+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. 14 | */ 15 | @interface UIButton (WebCache) 16 | 17 | /** 18 | * Get the current image URL. 19 | */ 20 | - (NSURL *)sd_currentImageURL; 21 | 22 | /** 23 | * Get the image URL for a control state. 24 | * 25 | * @param state Which state you want to know the URL for. The values are described in UIControlState. 26 | */ 27 | - (NSURL *)sd_imageURLForState:(UIControlState)state; 28 | 29 | /** 30 | * Set the imageView `image` with an `url`. 31 | * 32 | * The download is asynchronous and cached. 33 | * 34 | * @param url The url for the image. 35 | * @param state The state that uses the specified title. The values are described in UIControlState. 36 | */ 37 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state; 38 | 39 | /** 40 | * Set the imageView `image` with an `url` and a placeholder. 41 | * 42 | * The download is asynchronous and cached. 43 | * 44 | * @param url The url for the image. 45 | * @param state The state that uses the specified title. The values are described in UIControlState. 46 | * @param placeholder The image to be set initially, until the image request finishes. 47 | * @see sd_setImageWithURL:placeholderImage:options: 48 | */ 49 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; 50 | 51 | /** 52 | * Set the imageView `image` with an `url`, placeholder and custom options. 53 | * 54 | * The download is asynchronous and cached. 55 | * 56 | * @param url The url for the image. 57 | * @param state The state that uses the specified title. The values are described in UIControlState. 58 | * @param placeholder The image to be set initially, until the image request finishes. 59 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 60 | */ 61 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 62 | 63 | /** 64 | * Set the imageView `image` with an `url`. 65 | * 66 | * The download is asynchronous and cached. 67 | * 68 | * @param url The url for the image. 69 | * @param state The state that uses the specified title. The values are described in UIControlState. 70 | * @param completedBlock A block called when operation has been completed. This block has no return value 71 | * and takes the requested UIImage as first parameter. In case of error the image parameter 72 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 73 | * indicating if the image was retrived from the local cache or from the network. 74 | * The fourth parameter is the original image url. 75 | */ 76 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; 77 | 78 | /** 79 | * Set the imageView `image` with an `url`, placeholder. 80 | * 81 | * The download is asynchronous and cached. 82 | * 83 | * @param url The url for the image. 84 | * @param state The state that uses the specified title. The values are described in UIControlState. 85 | * @param placeholder The image to be set initially, until the image request finishes. 86 | * @param completedBlock A block called when operation has been completed. This block has no return value 87 | * and takes the requested UIImage as first parameter. In case of error the image parameter 88 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 89 | * indicating if the image was retrived from the local cache or from the network. 90 | * The fourth parameter is the original image url. 91 | */ 92 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 93 | 94 | /** 95 | * Set the imageView `image` with an `url`, placeholder and custom options. 96 | * 97 | * The download is asynchronous and cached. 98 | * 99 | * @param url The url for the image. 100 | * @param state The state that uses the specified title. The values are described in UIControlState. 101 | * @param placeholder The image to be set initially, until the image request finishes. 102 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 103 | * @param completedBlock A block called when operation has been completed. This block has no return value 104 | * and takes the requested UIImage as first parameter. In case of error the image parameter 105 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 106 | * indicating if the image was retrived from the local cache or from the network. 107 | * The fourth parameter is the original image url. 108 | */ 109 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 110 | 111 | /** 112 | * Set the backgroundImageView `image` with an `url`. 113 | * 114 | * The download is asynchronous and cached. 115 | * 116 | * @param url The url for the image. 117 | * @param state The state that uses the specified title. The values are described in UIControlState. 118 | */ 119 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; 120 | 121 | /** 122 | * Set the backgroundImageView `image` with an `url` and a placeholder. 123 | * 124 | * The download is asynchronous and cached. 125 | * 126 | * @param url The url for the image. 127 | * @param state The state that uses the specified title. The values are described in UIControlState. 128 | * @param placeholder The image to be set initially, until the image request finishes. 129 | * @see sd_setImageWithURL:placeholderImage:options: 130 | */ 131 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; 132 | 133 | /** 134 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options. 135 | * 136 | * The download is asynchronous and cached. 137 | * 138 | * @param url The url for the image. 139 | * @param state The state that uses the specified title. The values are described in UIControlState. 140 | * @param placeholder The image to be set initially, until the image request finishes. 141 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 142 | */ 143 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 144 | 145 | /** 146 | * Set the backgroundImageView `image` with an `url`. 147 | * 148 | * The download is asynchronous and cached. 149 | * 150 | * @param url The url for the image. 151 | * @param state The state that uses the specified title. The values are described in UIControlState. 152 | * @param completedBlock A block called when operation has been completed. This block has no return value 153 | * and takes the requested UIImage as first parameter. In case of error the image parameter 154 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 155 | * indicating if the image was retrived from the local cache or from the network. 156 | * The fourth parameter is the original image url. 157 | */ 158 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; 159 | 160 | /** 161 | * Set the backgroundImageView `image` with an `url`, placeholder. 162 | * 163 | * The download is asynchronous and cached. 164 | * 165 | * @param url The url for the image. 166 | * @param state The state that uses the specified title. The values are described in UIControlState. 167 | * @param placeholder The image to be set initially, until the image request finishes. 168 | * @param completedBlock A block called when operation has been completed. This block has no return value 169 | * and takes the requested UIImage as first parameter. In case of error the image parameter 170 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 171 | * indicating if the image was retrived from the local cache or from the network. 172 | * The fourth parameter is the original image url. 173 | */ 174 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 175 | 176 | /** 177 | * Set the backgroundImageView `image` with an `url`, placeholder and custom options. 178 | * 179 | * The download is asynchronous and cached. 180 | * 181 | * @param url The url for the image. 182 | * @param placeholder The image to be set initially, until the image request finishes. 183 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 184 | * @param completedBlock A block called when operation has been completed. This block has no return value 185 | * and takes the requested UIImage as first parameter. In case of error the image parameter 186 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 187 | * indicating if the image was retrived from the local cache or from the network. 188 | * The fourth parameter is the original image url. 189 | */ 190 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 191 | 192 | /** 193 | * Cancel the current image download 194 | */ 195 | - (void)sd_cancelImageLoadForState:(UIControlState)state; 196 | 197 | /** 198 | * Cancel the current backgroundImage download 199 | */ 200 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; 201 | 202 | @end 203 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIButton+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIButton+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLStorageKey; 14 | 15 | @implementation UIButton (WebCache) 16 | 17 | - (NSURL *)sd_currentImageURL { 18 | NSURL *url = self.imageURLStorage[@(self.state)]; 19 | 20 | if (!url) { 21 | url = self.imageURLStorage[@(UIControlStateNormal)]; 22 | } 23 | 24 | return url; 25 | } 26 | 27 | - (NSURL *)sd_imageURLForState:(UIControlState)state { 28 | return self.imageURLStorage[@(state)]; 29 | } 30 | 31 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state { 32 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 33 | } 34 | 35 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 36 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 37 | } 38 | 39 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 40 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 41 | } 42 | 43 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 44 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 45 | } 46 | 47 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 48 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 49 | } 50 | 51 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 52 | 53 | [self setImage:placeholder forState:state]; 54 | [self sd_cancelImageLoadForState:state]; 55 | 56 | if (!url) { 57 | [self.imageURLStorage removeObjectForKey:@(state)]; 58 | 59 | dispatch_main_async_safe(^{ 60 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 61 | if (completedBlock) { 62 | completedBlock(nil, error, SDImageCacheTypeNone, url); 63 | } 64 | }); 65 | 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak UIButton *wself = self; 72 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 73 | if (!wself) return; 74 | dispatch_main_sync_safe(^{ 75 | __strong UIButton *sself = wself; 76 | if (!sself) return; 77 | if (image) { 78 | [sself setImage:image forState:state]; 79 | } 80 | if (completedBlock && finished) { 81 | completedBlock(image, error, cacheType, url); 82 | } 83 | }); 84 | }]; 85 | [self sd_setImageLoadOperation:operation forState:state]; 86 | } 87 | 88 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 89 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 90 | } 91 | 92 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 93 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 94 | } 95 | 96 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 97 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 98 | } 99 | 100 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 101 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 102 | } 103 | 104 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 105 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 106 | } 107 | 108 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 109 | [self sd_cancelImageLoadForState:state]; 110 | 111 | [self setBackgroundImage:placeholder forState:state]; 112 | 113 | if (url) { 114 | __weak UIButton *wself = self; 115 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 116 | if (!wself) return; 117 | dispatch_main_sync_safe(^{ 118 | __strong UIButton *sself = wself; 119 | if (!sself) return; 120 | if (image) { 121 | [sself setBackgroundImage:image forState:state]; 122 | } 123 | if (completedBlock && finished) { 124 | completedBlock(image, error, cacheType, url); 125 | } 126 | }); 127 | }]; 128 | [self sd_setBackgroundImageLoadOperation:operation forState:state]; 129 | } else { 130 | dispatch_main_async_safe(^{ 131 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 132 | if (completedBlock) { 133 | completedBlock(nil, error, SDImageCacheTypeNone, url); 134 | } 135 | }); 136 | } 137 | } 138 | 139 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 140 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 141 | } 142 | 143 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 144 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 145 | } 146 | 147 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 148 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 149 | } 150 | 151 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 152 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 153 | } 154 | 155 | - (NSMutableDictionary *)imageURLStorage { 156 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 157 | if (!storage) 158 | { 159 | storage = [NSMutableDictionary dictionary]; 160 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 161 | } 162 | 163 | return storage; 164 | } 165 | 166 | @end 167 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+GIF.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.h 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (GIF) 12 | 13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name; 14 | 15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data; 16 | 17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+GIF.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.m 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "UIImage+GIF.h" 10 | #import 11 | 12 | @implementation UIImage (GIF) 13 | 14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data { 15 | if (!data) { 16 | return nil; 17 | } 18 | 19 | // 创建图像源 20 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 21 | 22 | // 获取图片帧数 23 | size_t count = CGImageSourceGetCount(source); 24 | 25 | UIImage *animatedImage; 26 | 27 | if (count <= 1) { 28 | animatedImage = [[UIImage alloc] initWithData:data]; 29 | } 30 | else { 31 | NSMutableArray *images = [NSMutableArray array]; 32 | 33 | NSTimeInterval duration = 0.0f; 34 | 35 | // 遍历并且提取所有的动画帧 36 | for (size_t i = 0; i < count; i++) { 37 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); 38 | 39 | // 累加动画时长 40 | duration += [self sd_frameDurationAtIndex:i source:source]; 41 | 42 | // 将图像添加到动画数组 43 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 44 | 45 | CGImageRelease(image); 46 | } 47 | 48 | if (!duration) { 49 | duration = (1.0f / 10.0f) * count; 50 | } 51 | 52 | // 建立可动画图像 53 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 54 | } 55 | 56 | CFRelease(source); 57 | 58 | return animatedImage; 59 | } 60 | 61 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 62 | float frameDuration = 0.1f; 63 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 64 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 65 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 66 | 67 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 68 | if (delayTimeUnclampedProp) { 69 | frameDuration = [delayTimeUnclampedProp floatValue]; 70 | } 71 | else { 72 | 73 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 74 | if (delayTimeProp) { 75 | frameDuration = [delayTimeProp floatValue]; 76 | } 77 | } 78 | 79 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 80 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 81 | // a duration of <= 10 ms. See and 82 | // for more information. 83 | 84 | if (frameDuration < 0.011f) { 85 | frameDuration = 0.100f; 86 | } 87 | 88 | CFRelease(cfFrameProperties); 89 | return frameDuration; 90 | } 91 | 92 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 93 | CGFloat scale = [UIScreen mainScreen].scale; 94 | 95 | if (scale > 1.0f) { 96 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 97 | 98 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 99 | 100 | if (data) { 101 | return [UIImage sd_animatedGIFWithData:data]; 102 | } 103 | 104 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 105 | 106 | data = [NSData dataWithContentsOfFile:path]; 107 | 108 | if (data) { 109 | return [UIImage sd_animatedGIFWithData:data]; 110 | } 111 | 112 | return [UIImage imageNamed:name]; 113 | } 114 | else { 115 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 116 | 117 | NSData *data = [NSData dataWithContentsOfFile:path]; 118 | 119 | if (data) { 120 | return [UIImage sd_animatedGIFWithData:data]; 121 | } 122 | 123 | return [UIImage imageNamed:name]; 124 | } 125 | } 126 | 127 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 128 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 129 | return self; 130 | } 131 | 132 | CGSize scaledSize = size; 133 | CGPoint thumbnailPoint = CGPointZero; 134 | 135 | CGFloat widthFactor = size.width / self.size.width; 136 | CGFloat heightFactor = size.height / self.size.height; 137 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 138 | scaledSize.width = self.size.width * scaleFactor; 139 | scaledSize.height = self.size.height * scaleFactor; 140 | 141 | if (widthFactor > heightFactor) { 142 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 143 | } 144 | else if (widthFactor < heightFactor) { 145 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 146 | } 147 | 148 | NSMutableArray *scaledImages = [NSMutableArray array]; 149 | 150 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 151 | 152 | for (UIImage *image in self.images) { 153 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 154 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 155 | 156 | [scaledImages addObject:newImage]; 157 | } 158 | 159 | UIGraphicsEndImageContext(); 160 | 161 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 162 | } 163 | 164 | @end 165 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+MultiFormat.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (MultiFormat) 12 | 13 | + (UIImage *)sd_imageWithData:(NSData *)data; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+MultiFormat.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "UIImage+MultiFormat.h" 10 | #import "UIImage+GIF.h" 11 | #import "NSData+ImageContentType.h" 12 | #import 13 | 14 | #ifdef SD_WEBP 15 | #import "UIImage+WebP.h" 16 | #endif 17 | 18 | @implementation UIImage (MultiFormat) 19 | 20 | + (UIImage *)sd_imageWithData:(NSData *)data { 21 | UIImage *image; 22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 23 | if ([imageContentType isEqualToString:@"image/gif"]) { 24 | image = [UIImage sd_animatedGIFWithData:data]; 25 | } 26 | #ifdef SD_WEBP 27 | else if ([imageContentType isEqualToString:@"image/webp"]) 28 | { 29 | image = [UIImage sd_imageWithWebPData:data]; 30 | } 31 | #endif 32 | else { 33 | image = [[UIImage alloc] initWithData:data]; 34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 35 | if (orientation != UIImageOrientationUp) { 36 | image = [UIImage imageWithCGImage:image.CGImage 37 | scale:image.scale 38 | orientation:orientation]; 39 | } 40 | } 41 | 42 | 43 | return image; 44 | } 45 | 46 | 47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 48 | UIImageOrientation result = UIImageOrientationUp; 49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 50 | if (imageSource) { 51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 52 | if (properties) { 53 | CFTypeRef val; 54 | int exifOrientation; 55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 56 | if (val) { 57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 59 | } // else - if it's not set it remains at up 60 | CFRelease((CFTypeRef) properties); 61 | } else { 62 | //NSLog(@"NO PROPERTIES, FAIL"); 63 | } 64 | CFRelease(imageSource); 65 | } 66 | return result; 67 | } 68 | 69 | #pragma mark EXIF orientation tag converter 70 | // Convert an EXIF image orientation to an iOS one. 71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 73 | UIImageOrientation orientation = UIImageOrientationUp; 74 | switch (exifOrientation) { 75 | case 1: 76 | orientation = UIImageOrientationUp; 77 | break; 78 | 79 | case 3: 80 | orientation = UIImageOrientationDown; 81 | break; 82 | 83 | case 8: 84 | orientation = UIImageOrientationLeft; 85 | break; 86 | 87 | case 6: 88 | orientation = UIImageOrientationRight; 89 | break; 90 | 91 | case 2: 92 | orientation = UIImageOrientationUpMirrored; 93 | break; 94 | 95 | case 4: 96 | orientation = UIImageOrientationDownMirrored; 97 | break; 98 | 99 | case 5: 100 | orientation = UIImageOrientationLeftMirrored; 101 | break; 102 | 103 | case 7: 104 | orientation = UIImageOrientationRightMirrored; 105 | break; 106 | default: 107 | break; 108 | } 109 | return orientation; 110 | } 111 | 112 | 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+WebP.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | 11 | #import 12 | 13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device 14 | void WebPInitPremultiplyNEON(void); 15 | 16 | void WebPInitUpsamplersNEON(void); 17 | 18 | void VP8DspInitNEON(void); 19 | 20 | @interface UIImage (WebP) 21 | 22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data; 23 | 24 | @end 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImage+WebP.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | #import "UIImage+WebP.h" 11 | #import "webp/decode.h" 12 | 13 | // Callback for CGDataProviderRelease 14 | static void FreeImageData(void *info, const void *data, size_t size) 15 | { 16 | free((void *)data); 17 | } 18 | 19 | @implementation UIImage (WebP) 20 | 21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data { 22 | WebPDecoderConfig config; 23 | if (!WebPInitDecoderConfig(&config)) { 24 | return nil; 25 | } 26 | 27 | if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) { 28 | return nil; 29 | } 30 | 31 | config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB; 32 | config.options.use_threads = 1; 33 | 34 | // Decode the WebP image data into a RGBA value array. 35 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) { 36 | return nil; 37 | } 38 | 39 | int width = config.input.width; 40 | int height = config.input.height; 41 | if (config.options.use_scaling) { 42 | width = config.options.scaled_width; 43 | height = config.options.scaled_height; 44 | } 45 | 46 | // Construct a UIImage from the decoded RGBA value array. 47 | CGDataProviderRef provider = 48 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData); 49 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 50 | CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0; 51 | size_t components = config.input.has_alpha ? 4 : 3; 52 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; 53 | CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); 54 | 55 | CGColorSpaceRelease(colorSpaceRef); 56 | CGDataProviderRelease(provider); 57 | 58 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; 59 | CGImageRelease(imageRef); 60 | 61 | return image; 62 | } 63 | 64 | @end 65 | 66 | #if !COCOAPODS 67 | // Functions to resolve some undefined symbols when using WebP and force_load flag 68 | void WebPInitPremultiplyNEON(void) {} 69 | void WebPInitUpsamplersNEON(void) {} 70 | void VP8DspInitNEON(void) {} 71 | #endif 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImageView+HighlightedWebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageManager.h" 12 | 13 | /** 14 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. 15 | */ 16 | @interface UIImageView (HighlightedWebCache) 17 | 18 | /** 19 | * Set the imageView `highlightedImage` with an `url`. 20 | * 21 | * The download is asynchronous and cached. 22 | * 23 | * @param url The url for the image. 24 | */ 25 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url; 26 | 27 | /** 28 | * Set the imageView `highlightedImage` with an `url` and custom options. 29 | * 30 | * The download is asynchronous and cached. 31 | * 32 | * @param url The url for the image. 33 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 34 | */ 35 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options; 36 | 37 | /** 38 | * Set the imageView `highlightedImage` with an `url`. 39 | * 40 | * The download is asynchronous and cached. 41 | * 42 | * @param url The url for the image. 43 | * @param completedBlock A block called when operation has been completed. This block has no return value 44 | * and takes the requested UIImage as first parameter. In case of error the image parameter 45 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 46 | * indicating if the image was retrived from the local cache or from the network. 47 | * The fourth parameter is the original image url. 48 | */ 49 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 50 | 51 | /** 52 | * Set the imageView `highlightedImage` with an `url` and custom options. 53 | * 54 | * The download is asynchronous and cached. 55 | * 56 | * @param url The url for the image. 57 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 58 | * @param completedBlock A block called when operation has been completed. This block has no return value 59 | * and takes the requested UIImage as first parameter. In case of error the image parameter 60 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 61 | * indicating if the image was retrived from the local cache or from the network. 62 | * The fourth parameter is the original image url. 63 | */ 64 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 65 | 66 | /** 67 | * Set the imageView `highlightedImage` with an `url` and custom options. 68 | * 69 | * The download is asynchronous and cached. 70 | * 71 | * @param url The url for the image. 72 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 73 | * @param progressBlock A block called while image is downloading 74 | * @param completedBlock A block called when operation has been completed. This block has no return value 75 | * and takes the requested UIImage as first parameter. In case of error the image parameter 76 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 77 | * indicating if the image was retrived from the local cache or from the network. 78 | * The fourth parameter is the original image url. 79 | */ 80 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 81 | 82 | /** 83 | * Cancel the current download 84 | */ 85 | - (void)sd_cancelCurrentHighlightedImageLoad; 86 | 87 | @end 88 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImageView+HighlightedWebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+HighlightedWebCache.h" 10 | #import "UIView+WebCacheOperation.h" 11 | 12 | #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" 13 | 14 | @implementation UIImageView (HighlightedWebCache) 15 | 16 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url { 17 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 18 | } 19 | 20 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 21 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 22 | } 23 | 24 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 25 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; 26 | } 27 | 28 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 29 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; 30 | } 31 | 32 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 33 | [self sd_cancelCurrentHighlightedImageLoad]; 34 | 35 | if (url) { 36 | __weak UIImageView *wself = self; 37 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 38 | if (!wself) return; 39 | dispatch_main_sync_safe (^ 40 | { 41 | if (!wself) return; 42 | if (image) { 43 | wself.highlightedImage = image; 44 | [wself setNeedsLayout]; 45 | } 46 | if (completedBlock && finished) { 47 | completedBlock(image, error, cacheType, url); 48 | } 49 | }); 50 | }]; 51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 52 | } else { 53 | dispatch_main_async_safe(^{ 54 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 55 | if (completedBlock) { 56 | completedBlock(nil, error, SDImageCacheTypeNone, url); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | - (void)sd_cancelCurrentHighlightedImageLoad { 63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImageView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView. 14 | * 15 | * Usage with a UITableViewCell sub-class: 16 | * 17 | * @code 18 | 19 | #import 20 | 21 | ... 22 | 23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 24 | { 25 | static NSString *MyIdentifier = @"MyIdentifier"; 26 | 27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 28 | 29 | if (cell == nil) { 30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] 31 | autorelease]; 32 | } 33 | 34 | // Here we use the provided sd_setImageWithURL: method to load the web image 35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image 36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 37 | placeholderImage:[UIImage imageNamed:@"placeholder"]]; 38 | 39 | cell.textLabel.text = @"My Text"; 40 | return cell; 41 | } 42 | 43 | * @endcode 44 | */ 45 | @interface UIImageView (WebCache) 46 | 47 | /** 48 | * Get the current image URL. 49 | * 50 | * Note that because of the limitations of categories this property can get out of sync 51 | * if you use sd_setImage: directly. 52 | */ 53 | - (NSURL *)sd_imageURL; 54 | 55 | /** 56 | * Set the imageView `image` with an `url`. 57 | * 58 | * The download is asynchronous and cached. 59 | * 60 | * @param url The url for the image. 61 | */ 62 | - (void)sd_setImageWithURL:(NSURL *)url; 63 | 64 | /** 65 | * Set the imageView `image` with an `url` and a placeholder. 66 | * 67 | * The download is asynchronous and cached. 68 | * 69 | * @param url The url for the image. 70 | * @param placeholder The image to be set initially, until the image request finishes. 71 | * @see sd_setImageWithURL:placeholderImage:options: 72 | */ 73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 74 | 75 | /** 76 | * Set the imageView `image` with an `url`, placeholder and custom options. 77 | * 78 | * The download is asynchronous and cached. 79 | * 80 | * @param url The url for the image. 81 | * @param placeholder The image to be set initially, until the image request finishes. 82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param completedBlock A block called when operation has been completed. This block has no return value 93 | * and takes the requested UIImage as first parameter. In case of error the image parameter 94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 95 | * indicating if the image was retrived from the local cache or from the network. 96 | * The fourth parameter is the original image url. 97 | */ 98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 99 | 100 | /** 101 | * Set the imageView `image` with an `url`, placeholder. 102 | * 103 | * The download is asynchronous and cached. 104 | * 105 | * @param url The url for the image. 106 | * @param placeholder The image to be set initially, until the image request finishes. 107 | * @param completedBlock A block called when operation has been completed. This block has no return value 108 | * and takes the requested UIImage as first parameter. In case of error the image parameter 109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 110 | * indicating if the image was retrived from the local cache or from the network. 111 | * The fourth parameter is the original image url. 112 | */ 113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 114 | 115 | /** 116 | * Set the imageView `image` with an `url`, placeholder and custom options. 117 | * 118 | * The download is asynchronous and cached. 119 | * 120 | * @param url The url for the image. 121 | * @param placeholder The image to be set initially, until the image request finishes. 122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 123 | * @param completedBlock A block called when operation has been completed. This block has no return value 124 | * and takes the requested UIImage as first parameter. In case of error the image parameter 125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 126 | * indicating if the image was retrived from the local cache or from the network. 127 | * The fourth parameter is the original image url. 128 | */ 129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 130 | 131 | /** 132 | * Set the imageView `image` with an `url`, placeholder and custom options. 133 | * 134 | * The download is asynchronous and cached. 135 | * 136 | * @param url The url for the image. 137 | * @param placeholder The image to be set initially, until the image request finishes. 138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 139 | * @param progressBlock A block called while image is downloading 140 | * @param completedBlock A block called when operation has been completed. This block has no return value 141 | * and takes the requested UIImage as first parameter. In case of error the image parameter 142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 143 | * indicating if the image was retrived from the local cache or from the network. 144 | * The fourth parameter is the original image url. 145 | */ 146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 147 | 148 | /** 149 | * Set the imageView `image` with an `url` and a optionaly placeholder image. 150 | * 151 | * The download is asynchronous and cached. 152 | * 153 | * @param url The url for the image. 154 | * @param placeholder The image to be set initially, until the image request finishes. 155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 156 | * @param progressBlock A block called while image is downloading 157 | * @param completedBlock A block called when operation has been completed. This block has no return value 158 | * and takes the requested UIImage as first parameter. In case of error the image parameter 159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 160 | * indicating if the image was retrived from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 164 | 165 | /** 166 | * Download an array of images and starts them in an animation loop 167 | * 168 | * @param arrayOfURLs An array of NSURL 169 | */ 170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; 171 | 172 | /** 173 | * Cancel the current download 174 | */ 175 | - (void)sd_cancelCurrentImageLoad; 176 | 177 | - (void)sd_cancelCurrentAnimationImagesLoad; 178 | 179 | @end 180 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIImageView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | 15 | @implementation UIImageView (WebCache) 16 | 17 | - (void)sd_setImageWithURL:(NSURL *)url { 18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 42 | // 取消当前图像下载 43 | [self sd_cancelCurrentImageLoad]; 44 | // 利用运行时retain url 45 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 46 | 47 | if (!(options & SDWebImageDelayPlaceholder)) { 48 | dispatch_main_async_safe(^{ 49 | // 设置占位图像 50 | self.image = placeholder; 51 | }); 52 | } 53 | 54 | if (url) { 55 | __weak UIImageView *wself = self; 56 | // 实例化 SDWebImageOperation 操作 57 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 58 | if (!wself) return; 59 | dispatch_main_sync_safe(^{ 60 | if (!wself) return; 61 | // 如果得到图像 62 | if (image) { 63 | // 记录图像 64 | wself.image = image; 65 | // 重绘视图 66 | [wself setNeedsLayout]; 67 | } else { 68 | // 如果没有得到图像 69 | // 如果设置了 SDWebImageDelayPlaceholder 选项 70 | if ((options & SDWebImageDelayPlaceholder)) { 71 | // 设置占位图像 72 | wself.image = placeholder; 73 | // 重绘视图 74 | [wself setNeedsLayout]; 75 | } 76 | } 77 | if (completedBlock && finished) { 78 | completedBlock(image, error, cacheType, url); 79 | } 80 | }); 81 | }]; 82 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 83 | } else { 84 | dispatch_main_async_safe(^{ 85 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 86 | if (completedBlock) { 87 | completedBlock(nil, error, SDImageCacheTypeNone, url); 88 | } 89 | }); 90 | } 91 | } 92 | 93 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 94 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 95 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 96 | 97 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 98 | } 99 | 100 | - (NSURL *)sd_imageURL { 101 | return objc_getAssociatedObject(self, &imageURLKey); 102 | } 103 | 104 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 105 | [self sd_cancelCurrentAnimationImagesLoad]; 106 | __weak UIImageView *wself = self; 107 | 108 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 109 | 110 | for (NSURL *logoImageURL in arrayOfURLs) { 111 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 112 | if (!wself) return; 113 | dispatch_main_sync_safe(^{ 114 | __strong UIImageView *sself = wself; 115 | [sself stopAnimating]; 116 | if (sself && image) { 117 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 118 | if (!currentImages) { 119 | currentImages = [[NSMutableArray alloc] init]; 120 | } 121 | [currentImages addObject:image]; 122 | 123 | sself.animationImages = currentImages; 124 | [sself setNeedsLayout]; 125 | } 126 | [sself startAnimating]; 127 | }); 128 | }]; 129 | [operationsArray addObject:operation]; 130 | } 131 | 132 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 133 | } 134 | 135 | - (void)sd_cancelCurrentImageLoad { 136 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 137 | } 138 | 139 | - (void)sd_cancelCurrentAnimationImagesLoad { 140 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 141 | } 142 | 143 | @end 144 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIView+WebCacheOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @interface UIView (WebCacheOperation) 13 | 14 | /** 15 | * Set the image load operation (storage in a UIView based dictionary) 16 | * 17 | * @param operation the operation 18 | * @param key key for storing the operation 19 | */ 20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; 21 | 22 | /** 23 | * Cancel all operations for the current UIView and key 24 | * 25 | * @param key key for identifying the operations 26 | */ 27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; 28 | 29 | /** 30 | * Just remove the operations corresponding to the current UIView and key without cancelling them 31 | * 32 | * @param key key for identifying the operations 33 | */ 34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Categories(分类)/UIView+WebCacheOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCacheOperation.h" 10 | #import "objc/runtime.h" 11 | 12 | static char loadOperationKey; 13 | 14 | @implementation UIView (WebCacheOperation) 15 | 16 | - (NSMutableDictionary *)operationDictionary { 17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); 18 | if (operations) { 19 | return operations; 20 | } 21 | operations = [NSMutableDictionary dictionary]; 22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 23 | return operations; 24 | } 25 | 26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { 27 | [self sd_cancelImageLoadOperationWithKey:key]; 28 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 29 | [operationDictionary setObject:operation forKey:key]; 30 | } 31 | 32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { 33 | // Cancel in progress downloader from queue 34 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 35 | id operations = [operationDictionary objectForKey:key]; 36 | if (operations) { 37 | if ([operations isKindOfClass:[NSArray class]]) { 38 | for (id operation in operations) { 39 | if (operation) { 40 | [operation cancel]; 41 | } 42 | } 43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ 44 | [(id) operations cancel]; 45 | } 46 | [operationDictionary removeObjectForKey:key]; 47 | } 48 | } 49 | 50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { 51 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 52 | [operationDictionary removeObjectForKey:key]; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Downloader(下载)/SDWebImageDownloader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { 14 | SDWebImageDownloaderLowPriority = 1 << 0, 15 | SDWebImageDownloaderProgressiveDownload = 1 << 1, 16 | 17 | /** 18 | * By default, request prevent the of NSURLCache. With this flag, NSURLCache 19 | * is used with default policies. 20 | * 默认情况下,请求不使用 NSURLCache。使用此标记,会使用 NSURLCache 和默认缓存策略 21 | */ 22 | SDWebImageDownloaderUseNSURLCache = 1 << 2, 23 | 24 | /** 25 | * Call completion block with nil image/imageData if the image was read from NSURLCache 26 | * 如果图像是从 NSURLCache 读取的,则调用 completion block 时,image/imageData 传入 nil 27 | * 28 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`). 29 | * (此标记要和 `SDWebImageDownloaderUseNSURLCache` 组合使用) 30 | */ 31 | 32 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, 33 | /** 34 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 35 | * 在 iOS 4+,当 App 进入后台后仍然会继续下载图像。这是向系统请求额外的后台时间以保证下载请求完成的 36 | * 37 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 38 | * 如果后台任务过期,请求将会被取消 39 | */ 40 | 41 | SDWebImageDownloaderContinueInBackground = 1 << 4, 42 | 43 | /** 44 | * Handles cookies stored in NSHTTPCookieStore by setting 45 | * 通过设置 46 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 47 | * 处理保存在 NSHTTPCookieStore 中的 cookies 48 | */ 49 | SDWebImageDownloaderHandleCookies = 1 << 5, 50 | 51 | /** 52 | * Enable to allow untrusted SSL ceriticates. 53 | * 允许不信任的 SSL 证书 54 | * 55 | * Useful for testing purposes. Use with caution in production. 56 | * 可以出于测试目的使用,在正式产品中慎用 57 | */ 58 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, 59 | 60 | /** 61 | * Put the image in the high priority queue. 62 | * 将图像放入高优先级队列 63 | */ 64 | SDWebImageDownloaderHighPriority = 1 << 7, 65 | 66 | 67 | }; 68 | 69 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 70 | /** 71 | * Default value. All download operations will execute in queue style (first-in-first-out). 72 | * 默认值。所有下载操作将按照队列的先进先出方式执行 73 | */ 74 | SDWebImageDownloaderFIFOExecutionOrder, 75 | 76 | /** 77 | * All download operations will execute in stack style (last-in-first-out). 78 | * 所有下载操作将按照堆栈的后进先出方式执行 79 | */ 80 | SDWebImageDownloaderLIFOExecutionOrder 81 | }; 82 | 83 | /** 84 | * 开始下载通知 85 | */ 86 | extern NSString *const SDWebImageDownloadStartNotification; 87 | /** 88 | * 停止下载通知 89 | */ 90 | extern NSString *const SDWebImageDownloadStopNotification; 91 | 92 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 93 | 94 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 95 | 96 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 97 | 98 | /** 99 | * Asynchronous downloader dedicated and optimized for image loading. 100 | *
专为加载图像设计并优化的异步下载器 101 | */ 102 | @interface SDWebImageDownloader : NSObject 103 | 104 | /** 105 | * 设置并发下载数,默认为6 106 | */ 107 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 108 | 109 | /** 110 | * Shows the current amount of downloads that still need to be downloaded 111 | *
显示仍需要下载的数量 112 | */ 113 | 114 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 115 | 116 | 117 | /** 118 | * The timeout value (in seconds) for the download operation. Default: 15.0. 119 | *
下载操作的超时时长(秒),默认:15秒 120 | */ 121 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 122 | 123 | 124 | /** 125 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 126 | *
修改下载操作执行顺序,默认值是 `SDWebImageDownloaderFIFOExecutionOrder` 127 | */ 128 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 129 | 130 | /** 131 | * Singleton method, returns the shared instance 132 | *
单例方法,返回共享实例 133 | * 134 | * @return global shared instance of downloader class 135 | *
下载器的全局共享实例 136 | */ 137 | + (SDWebImageDownloader *)sharedDownloader; 138 | 139 | /** 140 | * Set username 141 | *
设置用户名 142 | */ 143 | @property (strong, nonatomic) NSString *username; 144 | 145 | /** 146 | * Set password 147 | *
设置密码 148 | */ 149 | @property (strong, nonatomic) NSString *password; 150 | 151 | /** 152 | * Set filter to pick headers for downloading image HTTP request. 153 | *
设置下载图像 HTTP 请求头过滤器 154 | * 155 | * This block will be invoked for each downloading image request, returned 156 | * NSDictionary will be used as headers in corresponding HTTP request. 157 | *
此 block 将被每一个下载图像请求调用,返回的 NSDictionary 将被作为相应的 HTTP 请求头 158 | */ 159 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 160 | 161 | /** 162 | * Set a value for a HTTP header to be appended to each download HTTP request. 163 | *
为 HTTP 请求头设置一个值 164 | * 165 | * @param value The value for the header field. Use `nil` value to remove the header. 166 | *
请求头字段的值,使用 `nil` 删除该字段 167 | * @param field The name of the header field to set. 168 | *
要设置的请求头字段名 169 | */ 170 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 171 | 172 | /** 173 | * Returns the value of the specified HTTP header field. 174 | *
返回指定 HTTP 请求头字段的值 175 | * 176 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 177 | *
请求头字段的值,如果没有返回 `nil` 178 | */ 179 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 180 | 181 | /** 182 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 183 | * `NSOperation` to be used each time SDWebImage constructs a request 184 | * operation to download an image. 185 | *
设置 SDWebImage 每次构造下载图像请求操作的 `SDWebImageDownloaderOperation` 的子类 186 | * 187 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 188 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 189 | *
默认操作的 `SDWebImageDownloaderOperation` 的子类,传入 `nil` 将恢复为 `SDWebImageDownloaderOperation` 190 | */ 191 | - (void)setOperationClass:(Class)operationClass; 192 | 193 | /** 194 | * Creates a SDWebImageDownloader async downloader instance with a given URL 195 | *
使用给定的 URL 创建 SDWebImageDownloader 异步下载器实例 196 | * 197 | * The delegate will be informed when the image is finish downloaded or an error has happen. 198 | *
图像下载完成或者出现错误时会通知代理 199 | * 200 | * @see SDWebImageDownloaderDelegate 201 | * 202 | * @param url The URL to the image to download 203 | *
要下载的图像 URL 204 | * @param options The options to be used for this download 205 | *
下载选项 206 | * @param progressBlock A block called repeatedly while the image is downloading 207 | *
图像下载过程中被重复调用的 block,报告下载进度 208 | * @param completedBlock A block called once the download is completed. 209 | * If the download succeeded, the image parameter is set, in case of error, 210 | * error parameter is set with the error. The last parameter is always YES 211 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 212 | * SDWebImageDownloaderProgressiveDownload option, this block is called 213 | * repeatedly with the partial image object and the finished argument set to NO 214 | * before to be called a last time with the full image and finished argument 215 | * set to YES. In case of error, the finished argument is always YES. 216 | *
    217 | *
  • 图像下载完成后被调用一次的 block
  • 218 | *
  • 如果下载成功,image 参数会被设置
  • 219 | *
  • 如果出现错误,error 参数会被设置
  • 220 | *
  • 如果没有使用 SDWebImageDownloaderProgressiveDownload,最后一个参数一直是 YES
  • 221 | *
  • 如果使用了 SDWebImageDownloaderProgressiveDownload 选项,此 block 会被重复调用
  • 222 | *
      223 | *
    • 下载完成前,image 参数是部分图像,finished 参数是 NO
    • 224 | *
    • 最后一次被调用时,image 参数是完整图像,而 finished 参数是 YES
    • 225 | *
    226 | *
  • 如果出现错误,finished 参数也是 YES
  • 227 | *
228 | * 229 | * @return A cancellable SDWebImageOperation 230 | *
可被取消的 SDWebImageOperation 231 | */ 232 | - (id )downloadImageWithURL:(NSURL *)url 233 | options:(SDWebImageDownloaderOptions)options 234 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 235 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 236 | 237 | /** 238 | * Sets the download queue suspension state 239 | *
设置下载队列挂起状态 240 | */ 241 | - (void)setSuspended:(BOOL)suspended; 242 | 243 | @end 244 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Downloader(下载)/SDWebImageDownloader.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageDownloader.h" 10 | #import "SDWebImageDownloaderOperation.h" 11 | #import 12 | 13 | NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; 14 | NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; 15 | 16 | static NSString *const kProgressCallbackKey = @"progress"; 17 | static NSString *const kCompletedCallbackKey = @"completed"; 18 | 19 | @interface SDWebImageDownloader () 20 | 21 | @property (strong, nonatomic) NSOperationQueue *downloadQueue; 22 | @property (weak, nonatomic) NSOperation *lastAddedOperation; 23 | @property (assign, nonatomic) Class operationClass; 24 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks; 25 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; 26 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue 27 | // barrierQueue是一个串行队列,在一个单一队列中顺序处理所有下载操作的网络响应 28 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; 29 | 30 | @end 31 | 32 | @implementation SDWebImageDownloader 33 | 34 | + (void)initialize { 35 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) 36 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import 37 | if (NSClassFromString(@"SDNetworkActivityIndicator")) { 38 | 39 | #pragma clang diagnostic push 40 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 41 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; 42 | #pragma clang diagnostic pop 43 | 44 | // Remove observer in case it was previously added. 45 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; 46 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; 47 | 48 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 49 | selector:NSSelectorFromString(@"startActivity") 50 | name:SDWebImageDownloadStartNotification object:nil]; 51 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 52 | selector:NSSelectorFromString(@"stopActivity") 53 | name:SDWebImageDownloadStopNotification object:nil]; 54 | } 55 | } 56 | 57 | + (SDWebImageDownloader *)sharedDownloader { 58 | static dispatch_once_t once; 59 | static id instance; 60 | dispatch_once(&once, ^{ 61 | instance = [self new]; 62 | }); 63 | return instance; 64 | } 65 | 66 | - (id)init { 67 | if ((self = [super init])) { 68 | _operationClass = [SDWebImageDownloaderOperation class]; 69 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; 70 | _downloadQueue = [NSOperationQueue new]; 71 | _downloadQueue.maxConcurrentOperationCount = 6; 72 | _URLCallbacks = [NSMutableDictionary new]; 73 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"]; 74 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); 75 | _downloadTimeout = 15.0; 76 | } 77 | return self; 78 | } 79 | 80 | - (void)dealloc { 81 | [self.downloadQueue cancelAllOperations]; 82 | SDDispatchQueueRelease(_barrierQueue); 83 | } 84 | 85 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { 86 | if (value) { 87 | self.HTTPHeaders[field] = value; 88 | } 89 | else { 90 | [self.HTTPHeaders removeObjectForKey:field]; 91 | } 92 | } 93 | 94 | - (NSString *)valueForHTTPHeaderField:(NSString *)field { 95 | return self.HTTPHeaders[field]; 96 | } 97 | 98 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { 99 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; 100 | } 101 | 102 | - (NSUInteger)currentDownloadCount { 103 | return _downloadQueue.operationCount; 104 | } 105 | 106 | - (NSInteger)maxConcurrentDownloads { 107 | return _downloadQueue.maxConcurrentOperationCount; 108 | } 109 | 110 | - (void)setOperationClass:(Class)operationClass { 111 | _operationClass = operationClass ?: [SDWebImageDownloaderOperation class]; 112 | } 113 | 114 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { 115 | __block SDWebImageDownloaderOperation *operation; 116 | __weak SDWebImageDownloader *wself = self; 117 | 118 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ 119 | NSTimeInterval timeoutInterval = wself.downloadTimeout; 120 | if (timeoutInterval == 0.0) { 121 | timeoutInterval = 15.0; 122 | } 123 | 124 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise 125 | // 为防止重复缓存(NSURLCache + SDImageCache),如果设置了 SDWebImageDownloaderUseNSURLCache,则禁用 SDImageCache 126 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; 127 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); 128 | request.HTTPShouldUsePipelining = YES; 129 | if (wself.headersFilter) { 130 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); 131 | } 132 | else { 133 | request.allHTTPHeaderFields = wself.HTTPHeaders; 134 | } 135 | operation = [[wself.operationClass alloc] initWithRequest:request 136 | options:options 137 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 138 | SDWebImageDownloader *sself = wself; 139 | if (!sself) return; 140 | NSArray *callbacksForURL = [sself callbacksForURL:url]; 141 | for (NSDictionary *callbacks in callbacksForURL) { 142 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; 143 | if (callback) callback(receivedSize, expectedSize); 144 | } 145 | } 146 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { 147 | SDWebImageDownloader *sself = wself; 148 | if (!sself) return; 149 | NSArray *callbacksForURL = [sself callbacksForURL:url]; 150 | if (finished) { 151 | [sself removeCallbacksForURL:url]; 152 | } 153 | for (NSDictionary *callbacks in callbacksForURL) { 154 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; 155 | if (callback) callback(image, data, error, finished); 156 | } 157 | } 158 | cancelled:^{ 159 | SDWebImageDownloader *sself = wself; 160 | if (!sself) return; 161 | [sself removeCallbacksForURL:url]; 162 | }]; 163 | 164 | // 如果设置了用户名 & 口令 165 | if (wself.username && wself.password) { 166 | // 设置 https 访问时身份验证使用的凭据 167 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; 168 | } 169 | 170 | if (options & SDWebImageDownloaderHighPriority) { 171 | operation.queuePriority = NSOperationQueuePriorityHigh; 172 | } else if (options & SDWebImageDownloaderLowPriority) { 173 | operation.queuePriority = NSOperationQueuePriorityLow; 174 | } 175 | 176 | [wself.downloadQueue addOperation:operation]; 177 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { 178 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency 179 | [wself.lastAddedOperation addDependency:operation]; 180 | wself.lastAddedOperation = operation; 181 | } 182 | }]; 183 | 184 | return operation; 185 | } 186 | 187 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { 188 | // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. 189 | if (url == nil) { 190 | if (completedBlock != nil) { 191 | completedBlock(nil, nil, nil, NO); 192 | } 193 | return; 194 | } 195 | 196 | dispatch_barrier_sync(self.barrierQueue, ^{ 197 | BOOL first = NO; 198 | if (!self.URLCallbacks[url]) { 199 | self.URLCallbacks[url] = [NSMutableArray new]; 200 | first = YES; 201 | } 202 | 203 | // Handle single download of simultaneous download request for the same URL 204 | NSMutableArray *callbacksForURL = self.URLCallbacks[url]; 205 | NSMutableDictionary *callbacks = [NSMutableDictionary new]; 206 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; 207 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; 208 | [callbacksForURL addObject:callbacks]; 209 | self.URLCallbacks[url] = callbacksForURL; 210 | 211 | if (first) { 212 | createCallback(); 213 | } 214 | }); 215 | } 216 | 217 | - (NSArray *)callbacksForURL:(NSURL *)url { 218 | __block NSArray *callbacksForURL; 219 | dispatch_sync(self.barrierQueue, ^{ 220 | callbacksForURL = self.URLCallbacks[url]; 221 | }); 222 | return [callbacksForURL copy]; 223 | } 224 | 225 | - (void)removeCallbacksForURL:(NSURL *)url { 226 | dispatch_barrier_async(self.barrierQueue, ^{ 227 | [self.URLCallbacks removeObjectForKey:url]; 228 | }); 229 | } 230 | 231 | - (void)setSuspended:(BOOL)suspended { 232 | [self.downloadQueue setSuspended:suspended]; 233 | } 234 | 235 | @end 236 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Downloader(下载)/SDWebImageDownloaderOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageDownloader.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | @interface SDWebImageDownloaderOperation : NSOperation 14 | 15 | /** 16 | * The request used by the operation's connection. 17 | *
操作的连接使用的请求 18 | */ 19 | @property (strong, nonatomic, readonly) NSURLRequest *request; 20 | 21 | /** 22 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 23 | *
URL 连接是否询问保存连接身份验证的凭据,默认是 `YES` 24 | * 25 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 26 | *
这是在 `NSURLConnectionDelegate` 的 `-connectionShouldUseCredentialStorage:` 方法中的返回值 27 | */ 28 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 29 | 30 | /** 31 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 32 | *
在 `-connection:didReceiveAuthenticationChallenge:` 方法中身份验证使用的凭据 33 | * 34 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 35 | *
如果存在请求 URL 的用户名或密码的共享凭据,此凭据会被覆盖 36 | */ 37 | @property (nonatomic, strong) NSURLCredential *credential; 38 | 39 | /** 40 | * The SDWebImageDownloaderOptions for the receiver. 41 | *
下载选项 42 | */ 43 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 44 | 45 | /** 46 | * Initializes a `SDWebImageDownloaderOperation` object 47 | *
初始化一个 `SDWebImageDownloaderOperation` 对象 48 | * 49 | * @see SDWebImageDownloaderOperation 50 | * 51 | * @param request the URL request 52 | *
请求 53 | * @param options downloader options 54 | *
下载选项 55 | * @param progressBlock the block executed when a new chunk of data arrives. 56 | *
新的数据块到达时执行的 block(下载进度) 57 | * @note the progress block is executed on a background queue 58 | * @note progress block 在后台队列之行 59 | * @param completedBlock the block executed when the download is done. 60 | *
下载结束后执行的 block 61 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 62 | * @note 如果下载成功,completion block 在主队列执行。如果出现错误,block 可能会在后台队列执行 63 | * @param cancelBlock the block executed if the download (operation) is cancelled 64 | *
如果下载(操作)被取消,执行的 block 65 | * 66 | * @return the initialized instance 67 | *
初始化的实例 68 | */ 69 | - (id)initWithRequest:(NSURLRequest *)request 70 | options:(SDWebImageDownloaderOptions)options 71 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 72 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 73 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 74 | 75 | @end 76 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Downloader(下载)/SDWebImageDownloaderOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageDownloaderOperation.h" 10 | #import "SDWebImageDecoder.h" 11 | #import "UIImage+MultiFormat.h" 12 | #import 13 | #import "SDWebImageManager.h" 14 | 15 | @interface SDWebImageDownloaderOperation () 16 | 17 | @property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; 18 | @property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; 19 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; 20 | 21 | @property (assign, nonatomic, getter = isExecuting) BOOL executing; 22 | @property (assign, nonatomic, getter = isFinished) BOOL finished; 23 | @property (assign, nonatomic) NSInteger expectedSize; 24 | @property (strong, nonatomic) NSMutableData *imageData; 25 | @property (strong, nonatomic) NSURLConnection *connection; 26 | @property (strong, atomic) NSThread *thread; 27 | 28 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 29 | @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; 30 | #endif 31 | 32 | @end 33 | 34 | @implementation SDWebImageDownloaderOperation { 35 | size_t width, height; 36 | UIImageOrientation orientation; 37 | BOOL responseFromCached; 38 | } 39 | 40 | @synthesize executing = _executing; 41 | @synthesize finished = _finished; 42 | 43 | - (id)initWithRequest:(NSURLRequest *)request 44 | options:(SDWebImageDownloaderOptions)options 45 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 46 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 47 | cancelled:(SDWebImageNoParamsBlock)cancelBlock { 48 | if ((self = [super init])) { 49 | _request = request; 50 | _shouldUseCredentialStorage = YES; 51 | _options = options; 52 | _progressBlock = [progressBlock copy]; 53 | _completedBlock = [completedBlock copy]; 54 | _cancelBlock = [cancelBlock copy]; 55 | _executing = NO; 56 | _finished = NO; 57 | _expectedSize = 0; 58 | responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called 59 | } 60 | return self; 61 | } 62 | 63 | - (void)start { 64 | @synchronized (self) { 65 | if (self.isCancelled) { 66 | self.finished = YES; 67 | [self reset]; 68 | return; 69 | } 70 | 71 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 72 | if ([self shouldContinueWhenAppEntersBackground]) { 73 | __weak __typeof__ (self) wself = self; 74 | self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 75 | __strong __typeof (wself) sself = wself; 76 | 77 | if (sself) { 78 | [sself cancel]; 79 | 80 | [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId]; 81 | sself.backgroundTaskId = UIBackgroundTaskInvalid; 82 | } 83 | }]; 84 | } 85 | #endif 86 | 87 | self.executing = YES; 88 | self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; 89 | self.thread = [NSThread currentThread]; 90 | } 91 | 92 | [self.connection start]; 93 | 94 | if (self.connection) { 95 | if (self.progressBlock) { 96 | self.progressBlock(0, NSURLResponseUnknownLength); 97 | } 98 | dispatch_async(dispatch_get_main_queue(), ^{ 99 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; 100 | }); 101 | 102 | if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { 103 | // Make sure to run the runloop in our background thread so it can process downloaded data 104 | // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 105 | // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) 106 | CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); 107 | } 108 | else { 109 | CFRunLoopRun(); 110 | } 111 | 112 | if (!self.isFinished) { 113 | [self.connection cancel]; 114 | [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; 115 | } 116 | } 117 | else { 118 | if (self.completedBlock) { 119 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); 120 | } 121 | } 122 | 123 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 124 | if (self.backgroundTaskId != UIBackgroundTaskInvalid) { 125 | [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; 126 | self.backgroundTaskId = UIBackgroundTaskInvalid; 127 | } 128 | #endif 129 | } 130 | 131 | - (void)cancel { 132 | @synchronized (self) { 133 | if (self.thread) { 134 | [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; 135 | } 136 | else { 137 | [self cancelInternal]; 138 | } 139 | } 140 | } 141 | 142 | - (void)cancelInternalAndStop { 143 | if (self.isFinished) return; 144 | [self cancelInternal]; 145 | CFRunLoopStop(CFRunLoopGetCurrent()); 146 | } 147 | 148 | - (void)cancelInternal { 149 | if (self.isFinished) return; 150 | [super cancel]; 151 | if (self.cancelBlock) self.cancelBlock(); 152 | 153 | if (self.connection) { 154 | [self.connection cancel]; 155 | dispatch_async(dispatch_get_main_queue(), ^{ 156 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; 157 | }); 158 | 159 | // As we cancelled the connection, its callback won't be called and thus won't 160 | // maintain the isFinished and isExecuting flags. 161 | if (self.isExecuting) self.executing = NO; 162 | if (!self.isFinished) self.finished = YES; 163 | } 164 | 165 | [self reset]; 166 | } 167 | 168 | - (void)done { 169 | self.finished = YES; 170 | self.executing = NO; 171 | [self reset]; 172 | } 173 | 174 | - (void)reset { 175 | self.cancelBlock = nil; 176 | self.completedBlock = nil; 177 | self.progressBlock = nil; 178 | self.connection = nil; 179 | self.imageData = nil; 180 | self.thread = nil; 181 | } 182 | 183 | - (void)setFinished:(BOOL)finished { 184 | [self willChangeValueForKey:@"isFinished"]; 185 | _finished = finished; 186 | [self didChangeValueForKey:@"isFinished"]; 187 | } 188 | 189 | - (void)setExecuting:(BOOL)executing { 190 | [self willChangeValueForKey:@"isExecuting"]; 191 | _executing = executing; 192 | [self didChangeValueForKey:@"isExecuting"]; 193 | } 194 | 195 | - (BOOL)isConcurrent { 196 | return YES; 197 | } 198 | 199 | #pragma mark NSURLConnection (delegate) 200 | 201 | - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 202 | 203 | //'304 Not Modified' is an exceptional one 204 | // 服务器响应 "304-没有修改" 需要单独处理 205 | if ((![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) && [((NSHTTPURLResponse *)response) statusCode] != 304) { 206 | NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; 207 | self.expectedSize = expected; 208 | if (self.progressBlock) { 209 | self.progressBlock(0, expected); 210 | } 211 | 212 | self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; 213 | } 214 | else { 215 | NSUInteger code = [((NSHTTPURLResponse *)response) statusCode]; 216 | 217 | //This is the case when server returns '304 Not Modified'. It means that remote image is not changed. 218 | //In case of 304 we need just cancel the operation and return cached image from the cache. 219 | if (code == 304) { 220 | [self cancelInternal]; 221 | } else { 222 | [self.connection cancel]; 223 | } 224 | dispatch_async(dispatch_get_main_queue(), ^{ 225 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 226 | }); 227 | 228 | if (self.completedBlock) { 229 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); 230 | } 231 | CFRunLoopStop(CFRunLoopGetCurrent()); 232 | [self done]; 233 | } 234 | } 235 | 236 | - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 237 | [self.imageData appendData:data]; 238 | 239 | if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { 240 | // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ 241 | // Thanks to the author @Nyx0uf 242 | 243 | // Get the total bytes downloaded 244 | const NSInteger totalSize = self.imageData.length; 245 | 246 | // Update the data source, we must pass ALL the data, not just the new bytes 247 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL); 248 | 249 | if (width + height == 0) { 250 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 251 | if (properties) { 252 | NSInteger orientationValue = -1; 253 | CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); 254 | if (val) CFNumberGetValue(val, kCFNumberLongType, &height); 255 | val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); 256 | if (val) CFNumberGetValue(val, kCFNumberLongType, &width); 257 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 258 | if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); 259 | CFRelease(properties); 260 | 261 | // When we draw to Core Graphics, we lose orientation information, 262 | // which means the image below born of initWithCGIImage will be 263 | // oriented incorrectly sometimes. (Unlike the image born of initWithData 264 | // in connectionDidFinishLoading.) So save it here and pass it on later. 265 | orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; 266 | } 267 | 268 | } 269 | 270 | if (width + height > 0 && totalSize < self.expectedSize) { 271 | // Create the image 272 | CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); 273 | 274 | #ifdef TARGET_OS_IPHONE 275 | // Workaround for iOS anamorphic image 276 | if (partialImageRef) { 277 | const size_t partialHeight = CGImageGetHeight(partialImageRef); 278 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 279 | CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); 280 | CGColorSpaceRelease(colorSpace); 281 | if (bmContext) { 282 | CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); 283 | CGImageRelease(partialImageRef); 284 | partialImageRef = CGBitmapContextCreateImage(bmContext); 285 | CGContextRelease(bmContext); 286 | } 287 | else { 288 | CGImageRelease(partialImageRef); 289 | partialImageRef = nil; 290 | } 291 | } 292 | #endif 293 | 294 | if (partialImageRef) { 295 | UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; 296 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; 297 | UIImage *scaledImage = [self scaledImageForKey:key image:image]; 298 | image = [UIImage decodedImageWithImage:scaledImage]; 299 | CGImageRelease(partialImageRef); 300 | dispatch_main_sync_safe(^{ 301 | if (self.completedBlock) { 302 | self.completedBlock(image, nil, nil, NO); 303 | } 304 | }); 305 | } 306 | } 307 | 308 | CFRelease(imageSource); 309 | } 310 | 311 | if (self.progressBlock) { 312 | self.progressBlock(self.imageData.length, self.expectedSize); 313 | } 314 | } 315 | 316 | + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { 317 | switch (value) { 318 | case 1: 319 | return UIImageOrientationUp; 320 | case 3: 321 | return UIImageOrientationDown; 322 | case 8: 323 | return UIImageOrientationLeft; 324 | case 6: 325 | return UIImageOrientationRight; 326 | case 2: 327 | return UIImageOrientationUpMirrored; 328 | case 4: 329 | return UIImageOrientationDownMirrored; 330 | case 5: 331 | return UIImageOrientationLeftMirrored; 332 | case 7: 333 | return UIImageOrientationRightMirrored; 334 | default: 335 | return UIImageOrientationUp; 336 | } 337 | } 338 | 339 | - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { 340 | return SDScaledImageForKey(key, image); 341 | } 342 | 343 | - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { 344 | SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; 345 | @synchronized(self) { 346 | CFRunLoopStop(CFRunLoopGetCurrent()); 347 | self.thread = nil; 348 | self.connection = nil; 349 | dispatch_async(dispatch_get_main_queue(), ^{ 350 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 351 | }); 352 | } 353 | 354 | if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) { 355 | responseFromCached = NO; 356 | } 357 | 358 | if (completionBlock) { 359 | if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { 360 | completionBlock(nil, nil, nil, YES); 361 | } 362 | else { 363 | UIImage *image = [UIImage sd_imageWithData:self.imageData]; 364 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; 365 | image = [self scaledImageForKey:key image:image]; 366 | 367 | // Do not force decoding animated GIFs 368 | if (!image.images) { 369 | image = [UIImage decodedImageWithImage:image]; 370 | } 371 | if (CGSizeEqualToSize(image.size, CGSizeZero)) { 372 | completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); 373 | } 374 | else { 375 | completionBlock(image, self.imageData, nil, YES); 376 | } 377 | } 378 | } 379 | self.completionBlock = nil; 380 | [self done]; 381 | } 382 | 383 | - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 384 | @synchronized(self) { 385 | CFRunLoopStop(CFRunLoopGetCurrent()); 386 | self.thread = nil; 387 | self.connection = nil; 388 | dispatch_async(dispatch_get_main_queue(), ^{ 389 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 390 | }); 391 | } 392 | 393 | if (self.completedBlock) { 394 | self.completedBlock(nil, nil, error, YES); 395 | } 396 | self.completionBlock = nil; 397 | [self done]; 398 | } 399 | 400 | - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { 401 | responseFromCached = NO; // If this method is called, it means the response wasn't read from cache 402 | // 如果此方法被调用,说明响应不是从缓存读取的 403 | if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { 404 | // Prevents caching of responses 405 | return nil; 406 | } 407 | else { 408 | return cachedResponse; 409 | } 410 | } 411 | 412 | - (BOOL)shouldContinueWhenAppEntersBackground { 413 | return self.options & SDWebImageDownloaderContinueInBackground; 414 | } 415 | 416 | // 以下两个方法是 https 访问时使用的方法,关于凭据的设置部分代码在 SDWebImageDownloader.m 中搜索 username 就可以看到了 417 | - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { 418 | return self.shouldUseCredentialStorage; 419 | } 420 | 421 | - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ 422 | if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 423 | if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates) && 424 | [challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) { 425 | [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge]; 426 | } else { 427 | NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 428 | [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 429 | } 430 | } else { 431 | if ([challenge previousFailureCount] == 0) { 432 | if (self.credential) { 433 | [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; 434 | } else { 435 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 436 | } 437 | } else { 438 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 439 | } 440 | } 441 | } 442 | 443 | @end 444 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/SDWebImageCompat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Jamie Pinkham 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | 12 | #ifdef __OBJC_GC__ 13 | #error SDWebImage does not support Objective-C Garbage Collection 14 | #endif 15 | 16 | #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployement Target version < 5.0 18 | #endif 19 | 20 | #if !TARGET_OS_IPHONE 21 | #import 22 | #ifndef UIImage 23 | #define UIImage NSImage 24 | #endif 25 | #ifndef UIImageView 26 | #define UIImageView NSImageView 27 | #endif 28 | #else 29 | 30 | #import 31 | 32 | #endif 33 | 34 | #ifndef NS_ENUM 35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 36 | #endif 37 | 38 | #ifndef NS_OPTIONS 39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type 40 | #endif 41 | 42 | #if OS_OBJECT_USE_OBJC 43 | #undef SDDispatchQueueRelease 44 | #undef SDDispatchQueueSetterSementics 45 | #define SDDispatchQueueRelease(q) 46 | #define SDDispatchQueueSetterSementics strong 47 | #else 48 | #undef SDDispatchQueueRelease 49 | #undef SDDispatchQueueSetterSementics 50 | #define SDDispatchQueueRelease(q) (dispatch_release(q)) 51 | #define SDDispatchQueueSetterSementics assign 52 | #endif 53 | 54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); 55 | 56 | typedef void(^SDWebImageNoParamsBlock)(); 57 | 58 | #define dispatch_main_sync_safe(block)\ 59 | if ([NSThread isMainThread]) {\ 60 | block();\ 61 | } else {\ 62 | dispatch_sync(dispatch_get_main_queue(), block);\ 63 | } 64 | 65 | #define dispatch_main_async_safe(block)\ 66 | if ([NSThread isMainThread]) {\ 67 | block();\ 68 | } else {\ 69 | dispatch_async(dispatch_get_main_queue(), block);\ 70 | } 71 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/SDWebImageCompat.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImageCompat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 11/12/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if !__has_feature(objc_arc) 12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag 13 | #endif 14 | 15 | inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { 16 | if (!image) { 17 | return nil; 18 | } 19 | 20 | if ([image.images count] > 0) { 21 | NSMutableArray *scaledImages = [NSMutableArray array]; 22 | 23 | for (UIImage *tempImage in image.images) { 24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; 25 | } 26 | 27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; 28 | } 29 | else { 30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 31 | CGFloat scale = 1.0; 32 | if (key.length >= 8) { 33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) 34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; 35 | if (range.location != NSNotFound) { 36 | scale = 2.0; 37 | } 38 | } 39 | 40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 41 | image = scaledImage; 42 | } 43 | return image; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/SDWebImageOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | 11 | @protocol SDWebImageOperation 12 | 13 | - (void)cancel; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImageDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import 12 | #import "SDWebImageCompat.h" 13 | 14 | @interface UIImage (ForceDecode) 15 | 16 | + (UIImage *)decodedImageWithImage:(UIImage *)image; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImageDecoder.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import "SDWebImageDecoder.h" 12 | 13 | @implementation UIImage (ForceDecode) 14 | 15 | + (UIImage *)decodedImageWithImage:(UIImage *)image { 16 | if (image.images) { 17 | // Do not decode animated images 18 | return image; 19 | } 20 | 21 | CGImageRef imageRef = image.CGImage; 22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); 23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; 24 | 25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 27 | 28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); 29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || 30 | infoMask == kCGImageAlphaNoneSkipFirst || 31 | infoMask == kCGImageAlphaNoneSkipLast); 32 | 33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. 34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html 35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { 36 | // Unset the old alpha info. 37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 38 | 39 | // Set noneSkipFirst. 40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 41 | } 42 | // Some PNGs tell us they have alpha but only 3 components. Odd. 43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 44 | // Unset the old alpha info. 45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 47 | } 48 | 49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. 50 | CGContextRef context = CGBitmapContextCreate(NULL, 51 | imageSize.width, 52 | imageSize.height, 53 | CGImageGetBitsPerComponent(imageRef), 54 | 0, 55 | colorSpace, 56 | bitmapInfo); 57 | CGColorSpaceRelease(colorSpace); 58 | 59 | // If failed, return undecompressed image 60 | if (!context) return image; 61 | 62 | CGContextDrawImage(context, imageRect, imageRef); 63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); 64 | 65 | CGContextRelease(context); 66 | 67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; 68 | CGImageRelease(decompressedImageRef); 69 | return decompressedImage; 70 | } 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImageManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageOperation.h" 11 | #import "SDWebImageDownloader.h" 12 | #import "SDImageCache.h" 13 | 14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { 15 | /** 16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 17 | * 默认情况下,当一个 URL 下载失败,会将该 URL 放在黑名单中,不再尝试下载 18 | * 19 | * This flag disable this blacklisting. 20 | * 此标记取消黑名单 21 | */ 22 | SDWebImageRetryFailed = 1 << 0, 23 | 24 | /** 25 | * By default, image downloads are started during UI interactions, this flags disable this feature, 26 | * 默认情况下,在 UI 交互时也会启动图像下载,此标记取消这一特性 27 | * 28 | * leading to delayed download on UIScrollView deceleration for instance. 29 | * 会推迟到滚动视图停止滚动之后再继续下载 30 | * 备注:NSURLConnection 的网络下载事件监听的运行循环模式是 NSDefaultRunLoopMode 31 | */ 32 | SDWebImageLowPriority = 1 << 1, 33 | 34 | /** 35 | * This flag disables on-disk caching 36 | * 此标记取消磁盘缓存 37 | */ 38 | SDWebImageCacheMemoryOnly = 1 << 2, 39 | 40 | /** 41 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 42 | * 此标记允许渐进式下载,就像浏览器中那样,下载过程中,图像会逐步显示出来 43 | * 44 | * By default, the image is only displayed once completely downloaded. 45 | * 默认情况下,图像会在下载完成后一次性显示 46 | */ 47 | SDWebImageProgressiveDownload = 1 << 3, 48 | 49 | /** 50 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 51 | * 即使图像被缓存,遵守 HTPP 响应的缓存控制,如果需要,从远程刷新图像 52 | * 53 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 54 | * 磁盘缓存将由 NSURLCache 处理,而不是 SDWebImage,这会对性能有轻微的影响 55 | * 56 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 57 | * 此选项有助于处理同一个请求 URL 的图像发生变化 58 | * 59 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 60 | * 如果缓存的图像被刷新,会调用一次 completion block,并传递最终的图像 61 | * 62 | * Use this flag only if you can't make your URLs static with embeded cache busting parameter. 63 | * 仅在无法使用嵌入式缓存清理参数确定图像 URL 时,使用此标记 64 | */ 65 | SDWebImageRefreshCached = 1 << 4, 66 | 67 | /** 68 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 69 | * 在 iOS 4+,当 App 进入后台后仍然会继续下载图像。这是向系统请求额外的后台时间以保证下载请求完成的 70 | * 71 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 72 | * 如果后台任务过期,请求将会被取消 73 | */ 74 | SDWebImageContinueInBackground = 1 << 5, 75 | 76 | /** 77 | * Handles cookies stored in NSHTTPCookieStore by setting 78 | * 通过设置 79 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 80 | * 处理保存在 NSHTTPCookieStore 中的 cookies 81 | */ 82 | SDWebImageHandleCookies = 1 << 6, 83 | 84 | /** 85 | * Enable to allow untrusted SSL ceriticates. 86 | * 允许不信任的 SSL 证书 87 | * 88 | * Useful for testing purposes. Use with caution in production. 89 | * 可以出于测试目的使用,在正式产品中慎用 90 | */ 91 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 92 | 93 | /** 94 | * By default, image are loaded in the order they were queued. This flag move them to 95 | * 默认情况下,图像会按照在队列中的顺序被加载,此标记会将它们移动到队列前部立即被加载 96 | * 97 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 98 | * 而不是等待当前队列被加载,等待队列加载会需要一段时间 99 | * could take a while). 100 | */ 101 | SDWebImageHighPriority = 1 << 8, 102 | 103 | /** 104 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 105 | * 默认情况下,在加载图像时,占位图像已经会被加载。而此标记会延迟加载占位图像,直到图像已经完成加载 106 | * 107 | * of the placeholder image until after the image has finished loading. 108 | */ 109 | SDWebImageDelayPlaceholder = 1 << 9, 110 | 111 | /** 112 | * We usually don't call transformDownloadedImage delegate method on animated images, 113 | * 通常不会在可动画的图像上调用 transformDownloadedImage 代理方法,因为大多数转换代码会破坏动画文件 114 | * 115 | * as most transformation code would mangle it. 116 | * Use this flag to transform them anyway. 117 | * 使用此标记尝试转换 118 | */ 119 | SDWebImageTransformAnimatedImage = 1 << 10, 120 | }; 121 | 122 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 123 | 124 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 125 | 126 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 127 | 128 | 129 | @class SDWebImageManager; 130 | 131 | @protocol SDWebImageManagerDelegate 132 | 133 | @optional 134 | 135 | /** 136 | * Controls which image should be downloaded when the image is not found in the cache. 137 | * 138 | * @param imageManager The current `SDWebImageManager` 139 | * @param imageURL The url of the image to be downloaded 140 | * 141 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 142 | */ 143 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 144 | 145 | /** 146 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 147 | * NOTE: This method is called from a global queue in order to not to block the main thread. 148 | * 149 | * @param imageManager The current `SDWebImageManager` 150 | * @param image The image to transform 151 | * @param imageURL The url of the image to transform 152 | * 153 | * @return The transformed image object. 154 | */ 155 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 156 | 157 | @end 158 | 159 | /** 160 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 161 | *
SDWebImageManager 是 UIImageView+WebCache 等分类后台工作的类 162 | * 163 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 164 | *
是异步下载器 (SDWebImageDownloader) 和图像缓存存储 (SDImageCache) 之间的纽带 165 | * 166 | * You can use this class directly to benefit from web image downloading with caching in another context than 167 | * a UIView. 168 | *
可以直接使用此类实现 web 图像下载 169 | * 170 | * Here is a simple example of how to use SDWebImageManager: 171 | *
以下是如何使用 SDWebImageManager 的示例代码 172 | * 173 | * @code 174 | 175 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 176 | [manager downloadWithURL:imageURL 177 | options:0 178 | progress:nil 179 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 180 | if (image) { 181 | // do something with image 182 | } 183 | }]; 184 | 185 | * @endcode 186 | */ 187 | @interface SDWebImageManager : NSObject 188 | 189 | @property (weak, nonatomic) id delegate; 190 | 191 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 192 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 193 | 194 | /** 195 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 196 | * be used to remove dynamic part of an image URL. 197 | *
"缓存过滤器"是一个 block,用于每次 SDWebImageManager 需要将一个 URL 转换成一个缓存的键值,可用于删除图像 URL 中动态的部分 198 | * 199 | * The following example sets a filter in the application delegate that will remove any query-string from the 200 | * URL before to use it as a cache key: 201 | *
以下示例在 application 代理中设置一个过滤器,该过滤器会在将 URL 当作缓存键值之前,从 URL 中删除请求字符串 202 | * 203 | * @code 204 | 205 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 206 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 207 | return [url absoluteString]; 208 | }]; 209 | 210 | * @endcode 211 | */ 212 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 213 | 214 | /** 215 | * Returns global SDWebImageManager instance. 216 | *
返回全局的 SDWebImageManager 实例(单例) 217 | * 218 | * @return SDWebImageManager shared instance 219 | */ 220 | + (SDWebImageManager *)sharedManager; 221 | 222 | /** 223 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 224 | *
如果不存在缓存下载指定 URL 的图像,否则返回缓存的图像 225 | * 226 | * @param url The URL to the image 227 | * @param options A mask to specify options to use for this request 228 | * @param progressBlock A block called while image is downloading 229 | *
下载进度回调,后台线程 230 | * @param completedBlock A block called when operation has been completed. 231 | *
操作完成回调,主线程 232 | * 233 | * This parameter is required. 234 | *
此参数是必须的 235 | * 236 | * This block has no return value and takes the requested UIImage as first parameter. 237 | *
此block没有返回值,第一个参数是请求的 UIImage 238 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 239 | *
如果出现错误,image 参数是 nil,并且第二个参数会包含一个 NSError 240 | * 241 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache 242 | * or from the memory cache or from the network. 243 | *
第三个参数是一个 `SDImageCacheType` 枚举,标示该图像是从本地缓存加载,还是从内存缓存加载,还是从网络下载 244 | * 245 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 246 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the 247 | * block is called a last time with the full image and the last parameter set to YES. 248 | *
第四个参数,图像下载完成后返回 YES,如果使用 SDWebImageProgressiveDownload 选项,同时只获取到部分图片时,返回 NO 249 | * 250 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 251 | */ 252 | - (id )downloadImageWithURL:(NSURL *)url 253 | options:(SDWebImageOptions)options 254 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 255 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 256 | 257 | /** 258 | * Saves image to cache for given URL 259 | *
将图像保存成指定 URL 对应的缓存 260 | * 261 | * @param image The image to cache 262 | * @param url The URL to the image 263 | * 264 | */ 265 | 266 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 267 | 268 | /** 269 | * Cancel all current opreations 270 | *
取消当前所有操作 271 | */ 272 | - (void)cancelAll; 273 | 274 | /** 275 | * Check one or more operations running 276 | *
检查一个或多个操作是否正在运行 277 | */ 278 | - (BOOL)isRunning; 279 | 280 | /** 281 | * Check if image has already been cached 282 | *
检查图像是否已经被缓存 283 | * 284 | * @param url image url 285 | * 286 | * @return if the image was already cached 287 | */ 288 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 289 | 290 | /** 291 | * Check if image has already been cached on disk only 292 | *
检查图像是否存在磁盘缓存(此方法仅针对磁盘进行检查,只要存在就返回YES) 293 | * 294 | * @param url image url 295 | * 296 | * @return if the image was already cached (disk only) 297 | */ 298 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 299 | 300 | /** 301 | * Async check if image has already been cached 302 | *
异步检查图像是否已经存在缓存 303 | * 304 | * @param url image url 305 | * @param completionBlock the block to be executed when the check is finished 306 | * 307 | * @note the completion block is always executed on the main queue 308 | */ 309 | - (void)cachedImageExistsForURL:(NSURL *)url 310 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 311 | 312 | /** 313 | * Async check if image has already been cached on disk only 314 | *
异步检查图像是否已经存在缓存 315 | * 316 | * @param url image url 317 | * @param completionBlock the block to be executed when the check is finished 318 | * 319 | * @note the completion block is always executed on the main queue 320 | */ 321 | - (void)diskImageExistsForURL:(NSURL *)url 322 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 323 | 324 | 325 | /** 326 | *Return the cache key for a given URL 327 | *
返回指定 URL 的缓存键值,就是 URL 字符串 328 | */ 329 | - (NSString *)cacheKeyForURL:(NSURL *)url; 330 | 331 | @end 332 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImageManager.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageManager.h" 10 | #import 11 | 12 | @interface SDWebImageCombinedOperation : NSObject 13 | 14 | @property (assign, nonatomic, getter = isCancelled) BOOL cancelled; 15 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; 16 | @property (strong, nonatomic) NSOperation *cacheOperation; 17 | 18 | @end 19 | 20 | @interface SDWebImageManager () 21 | 22 | @property (strong, nonatomic, readwrite) SDImageCache *imageCache; 23 | @property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; 24 | @property (strong, nonatomic) NSMutableArray *failedURLs; 25 | @property (strong, nonatomic) NSMutableArray *runningOperations; 26 | 27 | @end 28 | 29 | @implementation SDWebImageManager 30 | 31 | + (id)sharedManager { 32 | static dispatch_once_t once; 33 | static id instance; 34 | dispatch_once(&once, ^{ 35 | instance = [self new]; 36 | }); 37 | return instance; 38 | } 39 | 40 | - (id)init { 41 | if ((self = [super init])) { 42 | _imageCache = [self createCache]; 43 | _imageDownloader = [SDWebImageDownloader sharedDownloader]; 44 | _failedURLs = [NSMutableArray new]; 45 | _runningOperations = [NSMutableArray new]; 46 | } 47 | return self; 48 | } 49 | 50 | - (SDImageCache *)createCache { 51 | return [SDImageCache sharedImageCache]; 52 | } 53 | 54 | - (NSString *)cacheKeyForURL:(NSURL *)url { 55 | if (self.cacheKeyFilter) { 56 | return self.cacheKeyFilter(url); 57 | } 58 | else { 59 | return [url absoluteString]; 60 | } 61 | } 62 | 63 | - (BOOL)cachedImageExistsForURL:(NSURL *)url { 64 | NSString *key = [self cacheKeyForURL:url]; 65 | if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; 66 | return [self.imageCache diskImageExistsWithKey:key]; 67 | } 68 | 69 | - (BOOL)diskImageExistsForURL:(NSURL *)url { 70 | NSString *key = [self cacheKeyForURL:url]; 71 | return [self.imageCache diskImageExistsWithKey:key]; 72 | } 73 | 74 | - (void)cachedImageExistsForURL:(NSURL *)url 75 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 76 | NSString *key = [self cacheKeyForURL:url]; 77 | 78 | BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); 79 | 80 | if (isInMemoryCache) { 81 | // making sure we call the completion block on the main queue 82 | dispatch_async(dispatch_get_main_queue(), ^{ 83 | if (completionBlock) { 84 | completionBlock(YES); 85 | } 86 | }); 87 | return; 88 | } 89 | 90 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 91 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 92 | if (completionBlock) { 93 | completionBlock(isInDiskCache); 94 | } 95 | }]; 96 | } 97 | 98 | - (void)diskImageExistsForURL:(NSURL *)url 99 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 100 | NSString *key = [self cacheKeyForURL:url]; 101 | 102 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 103 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 104 | if (completionBlock) { 105 | completionBlock(isInDiskCache); 106 | } 107 | }]; 108 | } 109 | 110 | - (id )downloadImageWithURL:(NSURL *)url 111 | options:(SDWebImageOptions)options 112 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 113 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { 114 | // Invoking this method without a completedBlock is pointless 115 | NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); 116 | 117 | // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't 118 | // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. 119 | if ([url isKindOfClass:NSString.class]) { 120 | url = [NSURL URLWithString:(NSString *)url]; 121 | } 122 | 123 | // Prevents app crashing on argument type error like sending NSNull instead of NSURL 124 | if (![url isKindOfClass:NSURL.class]) { 125 | url = nil; 126 | } 127 | 128 | __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; 129 | __weak SDWebImageCombinedOperation *weakOperation = operation; 130 | 131 | BOOL isFailedUrl = NO; 132 | @synchronized (self.failedURLs) { 133 | // 检查黑名单 134 | isFailedUrl = [self.failedURLs containsObject:url]; 135 | } 136 | 137 | if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { 138 | dispatch_main_sync_safe(^{ 139 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; 140 | completedBlock(nil, error, SDImageCacheTypeNone, YES, url); 141 | }); 142 | return operation; 143 | } 144 | 145 | @synchronized (self.runningOperations) { 146 | [self.runningOperations addObject:operation]; 147 | } 148 | NSString *key = [self cacheKeyForURL:url]; 149 | 150 | operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { 151 | if (operation.isCancelled) { 152 | @synchronized (self.runningOperations) { 153 | [self.runningOperations removeObject:operation]; 154 | } 155 | 156 | return; 157 | } 158 | 159 | if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { 160 | if (image && options & SDWebImageRefreshCached) { 161 | dispatch_main_sync_safe(^{ 162 | // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image 163 | // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. 164 | completedBlock(image, nil, cacheType, YES, url); 165 | }); 166 | } 167 | 168 | // download if no image or requested to refresh anyway, and download allowed by delegate 169 | SDWebImageDownloaderOptions downloaderOptions = 0; 170 | if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; 171 | if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; 172 | if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; 173 | if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; 174 | if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; 175 | if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; 176 | if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; 177 | if (image && options & SDWebImageRefreshCached) { 178 | // force progressive off if image already cached but forced refreshing 179 | downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; 180 | // ignore image read from NSURLCache if image if cached but force refreshing 181 | downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; 182 | } 183 | id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { 184 | if (weakOperation.isCancelled) { 185 | // Do nothing if the operation was cancelled 186 | // See #699 for more details 187 | // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data 188 | } 189 | else if (error) { 190 | dispatch_main_sync_safe(^{ 191 | if (!weakOperation.isCancelled) { 192 | completedBlock(nil, error, SDImageCacheTypeNone, finished, url); 193 | } 194 | }); 195 | 196 | if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) { 197 | @synchronized (self.failedURLs) { 198 | if (![self.failedURLs containsObject:url]) { 199 | [self.failedURLs addObject:url]; 200 | } 201 | } 202 | } 203 | } 204 | else { 205 | BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); 206 | 207 | if (options & SDWebImageRefreshCached && image && !downloadedImage) { 208 | // Image refresh hit the NSURLCache cache, do not call the completion block 209 | } 210 | else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { 211 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 212 | UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; 213 | 214 | if (transformedImage && finished) { 215 | BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; 216 | [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk]; 217 | } 218 | 219 | dispatch_main_sync_safe(^{ 220 | if (!weakOperation.isCancelled) { 221 | completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url); 222 | } 223 | }); 224 | }); 225 | } 226 | else { 227 | if (downloadedImage && finished) { 228 | [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; 229 | } 230 | 231 | dispatch_main_sync_safe(^{ 232 | if (!weakOperation.isCancelled) { 233 | completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url); 234 | } 235 | }); 236 | } 237 | } 238 | 239 | if (finished) { 240 | @synchronized (self.runningOperations) { 241 | [self.runningOperations removeObject:operation]; 242 | } 243 | } 244 | }]; 245 | operation.cancelBlock = ^{ 246 | [subOperation cancel]; 247 | 248 | @synchronized (self.runningOperations) { 249 | [self.runningOperations removeObject:weakOperation]; 250 | } 251 | }; 252 | } 253 | else if (image) { 254 | dispatch_main_sync_safe(^{ 255 | if (!weakOperation.isCancelled) { 256 | completedBlock(image, nil, cacheType, YES, url); 257 | } 258 | }); 259 | @synchronized (self.runningOperations) { 260 | [self.runningOperations removeObject:operation]; 261 | } 262 | } 263 | else { 264 | // Image not in cache and download disallowed by delegate 265 | dispatch_main_sync_safe(^{ 266 | if (!weakOperation.isCancelled) { 267 | completedBlock(nil, nil, SDImageCacheTypeNone, YES, url); 268 | } 269 | }); 270 | @synchronized (self.runningOperations) { 271 | [self.runningOperations removeObject:operation]; 272 | } 273 | } 274 | }]; 275 | 276 | return operation; 277 | } 278 | 279 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url { 280 | if (image && url) { 281 | NSString *key = [self cacheKeyForURL:url]; 282 | [self.imageCache storeImage:image forKey:key toDisk:YES]; 283 | } 284 | } 285 | 286 | - (void)cancelAll { 287 | @synchronized (self.runningOperations) { 288 | NSArray *copiedOperations = [self.runningOperations copy]; 289 | [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; 290 | [self.runningOperations removeObjectsInArray:copiedOperations]; 291 | } 292 | } 293 | 294 | - (BOOL)isRunning { 295 | return self.runningOperations.count > 0; 296 | } 297 | 298 | @end 299 | 300 | 301 | @implementation SDWebImageCombinedOperation 302 | 303 | - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock { 304 | // check if the operation is already cancelled, then we just call the cancelBlock 305 | if (self.isCancelled) { 306 | if (cancelBlock) { 307 | cancelBlock(); 308 | } 309 | _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes 310 | } else { 311 | _cancelBlock = [cancelBlock copy]; 312 | } 313 | } 314 | 315 | - (void)cancel { 316 | self.cancelled = YES; 317 | if (self.cacheOperation) { 318 | [self.cacheOperation cancel]; 319 | self.cacheOperation = nil; 320 | } 321 | if (self.cancelBlock) { 322 | self.cancelBlock(); 323 | 324 | // TODO: this is a temporary fix to #809. 325 | // Until we can figure the exact cause of the crash, going with the ivar instead of the setter 326 | // self.cancelBlock = nil; 327 | _cancelBlock = nil; 328 | } 329 | } 330 | 331 | @end 332 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImagePrefetcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @class SDWebImagePrefetcher; 13 | 14 | @protocol SDWebImagePrefetcherDelegate 15 | 16 | @optional 17 | 18 | /** 19 | * Called when an image was prefetched. 20 | * 21 | * @param imagePrefetcher The current image prefetcher 22 | * @param imageURL The image url that was prefetched 23 | * @param finishedCount The total number of images that were prefetched (successful or not) 24 | * @param totalCount The total number of images that were to be prefetched 25 | */ 26 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; 27 | 28 | /** 29 | * Called when all images are prefetched. 30 | * @param imagePrefetcher The current image prefetcher 31 | * @param totalCount The total number of images that were prefetched (whether successful or not) 32 | * @param skippedCount The total number of images that were skipped 33 | */ 34 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; 35 | 36 | @end 37 | 38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); 39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); 40 | 41 | /** 42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. 43 | */ 44 | @interface SDWebImagePrefetcher : NSObject 45 | 46 | /** 47 | * The web image manager 48 | */ 49 | @property (strong, nonatomic, readonly) SDWebImageManager *manager; 50 | 51 | /** 52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3. 53 | */ 54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; 55 | 56 | /** 57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. 58 | */ 59 | @property (nonatomic, assign) SDWebImageOptions options; 60 | 61 | @property (weak, nonatomic) id delegate; 62 | 63 | /** 64 | * Return the global image prefetcher instance. 65 | */ 66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 67 | 68 | /** 69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 70 | * currently one image is downloaded at a time, 71 | * and skips images for failed downloads and proceed to the next image in the list 72 | * 73 | * @param urls list of URLs to prefetch 74 | */ 75 | - (void)prefetchURLs:(NSArray *)urls; 76 | 77 | /** 78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 79 | * currently one image is downloaded at a time, 80 | * and skips images for failed downloads and proceed to the next image in the list 81 | * 82 | * @param urls list of URLs to prefetch 83 | * @param progressBlock block to be called when progress updates; 84 | * first parameter is the number of completed (successful or not) requests, 85 | * second parameter is the total number of images originally requested to be prefetched 86 | * @param completionBlock block to be called when prefetching is completed 87 | * first param is the number of completed (successful or not) requests, 88 | * second parameter is the number of skipped requests 89 | */ 90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 91 | 92 | /** 93 | * Remove and cancel queued list 94 | */ 95 | - (void)cancelPrefetching; 96 | 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-Chinese/SDWebImage/Utils(工具)/SDWebImagePrefetcher.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImagePrefetcher.h" 10 | 11 | #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) 12 | #define NSLog(...) 13 | #endif 14 | 15 | @interface SDWebImagePrefetcher () 16 | 17 | @property (strong, nonatomic) SDWebImageManager *manager; 18 | @property (strong, nonatomic) NSArray *prefetchURLs; 19 | @property (assign, nonatomic) NSUInteger requestedCount; 20 | @property (assign, nonatomic) NSUInteger skippedCount; 21 | @property (assign, nonatomic) NSUInteger finishedCount; 22 | @property (assign, nonatomic) NSTimeInterval startedTime; 23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 25 | 26 | @end 27 | 28 | @implementation SDWebImagePrefetcher 29 | 30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 31 | static dispatch_once_t once; 32 | static id instance; 33 | dispatch_once(&once, ^{ 34 | instance = [self new]; 35 | }); 36 | return instance; 37 | } 38 | 39 | - (id)init { 40 | if ((self = [super init])) { 41 | _manager = [SDWebImageManager new]; 42 | _options = SDWebImageLowPriority; 43 | self.maxConcurrentDownloads = 3; 44 | } 45 | return self; 46 | } 47 | 48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 50 | } 51 | 52 | - (NSUInteger)maxConcurrentDownloads { 53 | return self.manager.imageDownloader.maxConcurrentDownloads; 54 | } 55 | 56 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 57 | if (index >= self.prefetchURLs.count) return; 58 | self.requestedCount++; 59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 60 | if (!finished) return; 61 | self.finishedCount++; 62 | 63 | if (image) { 64 | if (self.progressBlock) { 65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 66 | } 67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); 74 | 75 | // Add last failed 76 | self.skippedCount++; 77 | } 78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 79 | [self.delegate imagePrefetcher:self 80 | didPrefetchURL:self.prefetchURLs[index] 81 | finishedCount:self.finishedCount 82 | totalCount:self.prefetchURLs.count 83 | ]; 84 | } 85 | 86 | if (self.prefetchURLs.count > self.requestedCount) { 87 | dispatch_async(dispatch_get_main_queue(), ^{ 88 | [self startPrefetchingAtIndex:self.requestedCount]; 89 | }); 90 | } 91 | else if (self.finishedCount == self.requestedCount) { 92 | [self reportStatus]; 93 | if (self.completionBlock) { 94 | self.completionBlock(self.finishedCount, self.skippedCount); 95 | self.completionBlock = nil; 96 | } 97 | } 98 | }]; 99 | } 100 | 101 | - (void)reportStatus { 102 | NSUInteger total = [self.prefetchURLs count]; 103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); 104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 105 | [self.delegate imagePrefetcher:self 106 | didFinishWithTotalCount:(total - self.skippedCount) 107 | skippedCount:self.skippedCount 108 | ]; 109 | } 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls { 113 | [self prefetchURLs:urls progress:nil completed:nil]; 114 | } 115 | 116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 117 | [self cancelPrefetching]; // Prevent duplicate prefetch request 118 | self.startedTime = CFAbsoluteTimeGetCurrent(); 119 | self.prefetchURLs = urls; 120 | self.completionBlock = completionBlock; 121 | self.progressBlock = progressBlock; 122 | 123 | if(urls.count == 0){ 124 | if(completionBlock){ 125 | completionBlock(0,0); 126 | } 127 | }else{ 128 | // Starts prefetching from the very first image on the list with the max allowed concurrency 129 | NSUInteger listCount = self.prefetchURLs.count; 130 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 131 | [self startPrefetchingAtIndex:i]; 132 | } 133 | } 134 | } 135 | 136 | - (void)cancelPrefetching { 137 | self.prefetchURLs = nil; 138 | self.skippedCount = 0; 139 | self.requestedCount = 0; 140 | self.finishedCount = 0; 141 | [self.manager cancelAll]; 142 | } 143 | 144 | @end 145 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-ChineseTests/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 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-ChineseTests/SDWebImage_translateTo_ChineseTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImage_translateTo_ChineseTests.m 3 | // SDWebImage-translateTo-ChineseTests 4 | // 5 | // Created by Macx on 15/10/7. 6 | // Copyright © 2015年 CYX. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface SDWebImage_translateTo_ChineseTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation SDWebImage_translateTo_ChineseTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-ChineseUITests/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 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /SDWebImage-translateTo-Chinese/SDWebImage-translateTo-ChineseUITests/SDWebImage_translateTo_ChineseUITests.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImage_translateTo_ChineseUITests.m 3 | // SDWebImage-translateTo-ChineseUITests 4 | // 5 | // Created by Macx on 15/10/7. 6 | // Copyright © 2015年 CYX. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface SDWebImage_translateTo_ChineseUITests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation SDWebImage_translateTo_ChineseUITests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | 22 | // In UI tests it is usually best to stop immediately when a failure occurs. 23 | self.continueAfterFailure = NO; 24 | // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. 25 | [[[XCUIApplication alloc] init] launch]; 26 | 27 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. 28 | } 29 | 30 | - (void)tearDown { 31 | // Put teardown code here. This method is called after the invocation of each test method in the class. 32 | [super tearDown]; 33 | } 34 | 35 | - (void)testExample { 36 | // Use recording to get started writing UI tests. 37 | // Use XCTAssert and related functions to verify your tests produce the correct results. 38 | } 39 | 40 | @end 41 | --------------------------------------------------------------------------------