Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

README.md 13 KiB

3 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. Web Image
  2. =========
  3. [![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage)
  4. [![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
  5. [![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
  6. [![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html)
  7. [![Dependency Status](https://www.versioneye.com/objective-c/sdwebimage/3.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/3.3)
  8. [![Reference Status](https://www.versioneye.com/objective-c/sdwebimage/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/references)
  9. [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/rs/SDWebImage)
  10. This library provides a category for UIImageView with support for remote images coming from the web.
  11. It provides:
  12. - An `UIImageView` category adding web image and cache management to the Cocoa Touch framework
  13. - An asynchronous image downloader
  14. - An asynchronous memory + disk image caching with automatic cache expiration handling
  15. - Animated GIF support
  16. - WebP format support
  17. - A background image decompression
  18. - A guarantee that the same URL won't be downloaded several times
  19. - A guarantee that bogus URLs won't be retried again and again
  20. - A guarantee that main thread will never be blocked
  21. - Performances!
  22. - Use GCD and ARC
  23. - Arm64 support
  24. NOTE: The version 3.0 of SDWebImage isn't fully backward compatible with 2.0 and requires iOS 5.1.1
  25. minimum deployment version. If you need iOS < 5.0 support, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat).
  26. [How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F)
  27. Who Uses It
  28. ----------
  29. Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list.
  30. How To Use
  31. ----------
  32. API documentation is available at [CocoaDocs - SDWebImage](http://cocoadocs.org/docsets/SDWebImage/)
  33. ### Using UIImageView+WebCache category with UITableView
  34. Just #import the UIImageView+WebCache.h header, and call the sd_setImageWithURL:placeholderImage:
  35. method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be
  36. handled for you, from async downloads to caching management.
  37. ```objective-c
  38. #import <SDWebImage/UIImageView+WebCache.h>
  39. ...
  40. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  41. static NSString *MyIdentifier = @"MyIdentifier";
  42. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
  43. if (cell == nil) {
  44. cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
  45. reuseIdentifier:MyIdentifier] autorelease];
  46. }
  47. // Here we use the new provided sd_setImageWithURL: method to load the web image
  48. [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
  49. placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
  50. cell.textLabel.text = @"My Text";
  51. return cell;
  52. }
  53. ```
  54. ### Using blocks
  55. With blocks, you can be notified about the image download progress and whenever the image retrieval
  56. has completed with success or not:
  57. ```objective-c
  58. // Here we use the new provided sd_setImageWithURL: method to load the web image
  59. [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
  60. placeholderImage:[UIImage imageNamed:@"placeholder.png"]
  61. completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
  62. ... completion code here ...
  63. }];
  64. ```
  65. Note: neither your success nor failure block will be call if your image request is canceled before completion.
  66. ### Using SDWebImageManager
  67. The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the
  68. asynchronous downloader with the image cache store. You can use this class directly to benefit
  69. from web image downloading with caching in another context than a UIView (ie: with Cocoa).
  70. Here is a simple example of how to use SDWebImageManager:
  71. ```objective-c
  72. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  73. [manager downloadImageWithURL:imageURL
  74. options:0
  75. progress:^(NSInteger receivedSize, NSInteger expectedSize) {
  76. // progression tracking code
  77. }
  78. completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  79. if (image) {
  80. // do something with image
  81. }
  82. }];
  83. ```
  84. ### Using Asynchronous Image Downloader Independently
  85. It's also possible to use the async image downloader independently:
  86. ```objective-c
  87. SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
  88. [downloader downloadImageWithURL:imageURL
  89. options:0
  90. progress:^(NSInteger receivedSize, NSInteger expectedSize) {
  91. // progression tracking code
  92. }
  93. completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
  94. if (image && finished) {
  95. // do something with image
  96. }
  97. }];
  98. ```
  99. ### Using Asynchronous Image Caching Independently
  100. It is also possible to use the async based image cache store independently. SDImageCache
  101. maintains a memory cache and an optional disk cache. Disk cache write operations are performed
  102. asynchronous so it doesn't add unnecessary latency to the UI.
  103. The SDImageCache class provides a singleton instance for convenience but you can create your own
  104. instance if you want to create separated cache namespace.
  105. To lookup the cache, you use the `queryDiskCacheForKey:done:` method. If the method returns nil, it means the cache
  106. doesn't currently own the image. You are thus responsible for generating and caching it. The cache
  107. key is an application unique identifier for the image to cache. It is generally the absolute URL of
  108. the image.
  109. ```objective-c
  110. SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
  111. [imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) {
  112. // image is not nil if image was found
  113. }];
  114. ```
  115. By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache.
  116. You can prevent this from happening by calling the alternative method `imageFromMemoryCacheForKey:`.
  117. To store an image into the cache, you use the storeImage:forKey: method:
  118. ```objective-c
  119. [[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
  120. ```
  121. By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If
  122. you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative
  123. third argument.
  124. ### Using cache key filter
  125. Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic
  126. (i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that
  127. takes the NSURL as input, and output a cache key NSString.
  128. The following example sets a filter in the application delegate that will remove any query-string from
  129. the URL before to use it as a cache key:
  130. ```objective-c
  131. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  132. SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) {
  133. url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
  134. return [url absoluteString];
  135. };
  136. // Your app init code...
  137. return YES;
  138. }
  139. ```
  140. Common Problems
  141. ---------------
  142. ### Using dynamic image size with UITableViewCell
  143. UITableView determines the size of the image by the first image set for a cell. If your remote images
  144. don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue.
  145. The following article gives a way to workaround this issue:
  146. [http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/)
  147. ### Handle image refresh
  148. SDWebImage does very aggressive caching by default. It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. It implies your images URLs are static URLs pointing to images that never change. If the pointed image happen to change, some parts of the URL should change accordingly.
  149. If you don't control the image server you're using, you may not be able to change the URL when its content is updated. This is the case for Facebook avatar URLs for instance. In such case, you may use the `SDWebImageRefreshCached` flag. This will slightly degrade the performance but will respect the HTTP caching control headers:
  150. ``` objective-c
  151. [imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
  152. placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
  153. options:SDWebImageRefreshCached];
  154. ```
  155. ### Add a progress indicator
  156. See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
  157. Installation
  158. ------------
  159. There are three ways to use SDWebImage in your project:
  160. - using CocoaPods
  161. - copying all the files into your project
  162. - importing the project as a static library
  163. ### Installation with CocoaPods
  164. [CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details.
  165. #### Podfile
  166. ```
  167. platform :ios, '6.1'
  168. pod 'SDWebImage', '~>3.7'
  169. ```
  170. If you are using Swift, be sure to add `use_frameworks!` and set your target to iOS 8+:
  171. ```
  172. platform :ios, '8.0'
  173. use_frameworks!
  174. ```
  175. #### Subspecs
  176. There are 3 subspecs available now: `Core`, `MapKit` and `WebP` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `WebP`, you need to specify it).
  177. Podfile example:
  178. ```
  179. pod 'SDWebImage/WebP'
  180. ```
  181. ### Installation with Carthage (iOS 8+)
  182. [Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods.
  183. To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage)
  184. #### Cartfile
  185. ```
  186. github "rs/SDWebImage"
  187. ```
  188. #### Usage
  189. Swift
  190. If you installed using CocoaPods:
  191. ```
  192. import SDWebImage
  193. ```
  194. If you installed manually:
  195. ```
  196. import WebImage
  197. ```
  198. Objective-C
  199. ```
  200. @import WebImage;
  201. ```
  202. ### Installation by cloning the repository
  203. In order to gain access to all the files from the repository, you should clone it.
  204. ```
  205. git clone --recursive https://github.com/rs/SDWebImage.git
  206. ```
  207. ### Add the SDWebImage project to your project
  208. - Download and unzip the last version of the framework from the [download page](https://github.com/rs/SDWebImage/releases)
  209. - Right-click on the project navigator and select "Add Files to "Your Project":
  210. - In the dialog, select SDWebImage.framework:
  211. - Check the "Copy items into destination group's folder (if needed)" checkbox
  212. ### Add dependencies
  213. - In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block:
  214. - Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature:
  215. ### Add Linker Flag
  216. Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag:
  217. ![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg)
  218. Alternatively, if this causes compilation problems with frameworks that extend optional libraries, such as Parse, RestKit or opencv2, instead of the -ObjC flag use:
  219. ```
  220. -force_load SDWebImage.framework/Versions/Current/SDWebImage
  221. ```
  222. If you're using Cocoa Pods and have any frameworks that extend optional libraries, such as Parsen RestKit or opencv2, instead of the -ObjC flag use:
  223. ```
  224. -force_load $(TARGET_BUILD_DIR)/libPods.a
  225. ```
  226. and this:
  227. ```
  228. $(inherited)
  229. ```
  230. ### Import headers in your source files
  231. In the source files where you need to use the library, import the header file:
  232. ```objective-c
  233. #import <SDWebImage/UIImageView+WebCache.h>
  234. ```
  235. ### Build Project
  236. At this point your workspace should build without error. If you are having problem, post to the Issue and the
  237. community can help you solve it.
  238. Future Enhancements
  239. -------------------
  240. - LRU memory cache cleanup instead of reset on memory warning
  241. ## Licenses
  242. All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE).