SDWebImage is a library for asynchronous image loading on iOS and macOS, providing a unified API for working with the network, cache, and animations. According to the official repository, the library is used in more than 100,000 projects and supports GIF, WebP, SVG, and progressive loading. SDWebImage provides automatic disk and memory caching, as well as integration with UIKit and SwiftUI.
Key Takeaways
SDWebImage is a library for asynchronous image loading on Apple platforms (iOS, macOS, tvOS, watchOS). It provides a UIImageView category with the sd_setImage method, which loads, caches, and displays an image from any source in a single line of code.
The library supports progressive loading (the image appears as bytes are received), animated images (GIF, APNG), transformations (rounding, cropping, watermarking), and custom decoders. According to GitHub Stats, SDWebImage has over 25,000 stars and is used in major applications, including Twitter, Pinterest, and Instagram.
The architecture is built on a component chain: Coder (decoding), Cache (storage), Loader (network), and Transformer (processing). Each component is replaceable, allowing the library to be adapted to specific project requirements.
SDWebImageManager is the central component that coordinates the loading process. It accepts a URL, checks the cache, loads data, decodes it into a UIImage, and passes it to the ImageView or Completion Handler. The manager operates through a shared singleton, accessible from anywhere in the application.
The manager sequentially checks Memory Cache (NSDictionary with UIImage), then Disk Cache (file system). On a miss, a network request is made via NSURLSession. After loading, the data is decoded, passes through transformations, and is saved to both caches. The entire process runs in a background queue, with results delivered to the main queue.
UIImageView+WebCache is an Objective-C category (accessible from Swift) that adds the sd_setImage method. This method accepts a URL, placeholder, options (SDWebImageOptions), and a completion block. The category automatically cancels the previous request when a table cell is reused through the sd_cancelCurrentImageLoad mechanism.
The SDWebImage architecture is divided into several modules with clear responsibility zones. Each class solves one task — from loading to display.
SDWebImageManager is the facade for all image operations. It contains references to ImageCache (SDImageCache) and ImageLoader (SDWebImageDownloader). Through the SDWebImageManagerDelegate, you can intercept loading and change the URL or behavior.
SDImageCache is a two-level cache (memory + disk) initialized with a unique namespace. Memory Cache stores UIImage with a configurable limit (by default — until system memory warning). Disk Cache stores data in the Library/Caches directory with a configurable storage duration (default 7 days).
SDWebImageDownloader is an HTTP client based on NSURLSession with support for headers, timeouts, and retries. The downloader deduplicates identical requests into a single network call and distributes the result among all subscribers.
SDWebImage implements two-level caching with a deterministic check order: first memory, then disk. The cache key is the absolute image URL without query parameters or its MD5 hash.
| Level | Storage Type | Content | Limit |
|---|---|---|---|
| Memory Cache | NSCache (NSDictionary) | UIImage (decoded Bitmap) | Until memory warning |
| Disk Cache | File system | NSData (JPEG/PNG/WebP) | 7 days TTL (configurable) |
| Auto Purge Cache | Memory + Disk | Combined framework cache | Configurable file size |
On receiving a memory warning, iOS notifies SDImageCache through UIApplicationDidReceiveMemoryWarningNotification, after which the Memory Cache is completely cleared. Disk Cache is cleared by TTL or when the limit is exceeded, sorting files by last access date.
For manual cache management, the following methods are available: clearMemory, clearDisk, calculateSize. Caching can be disabled for specific requests using the SDWebImageCacheMemoryOnly or SDWebImageAvoidAutoSetImage options.
SDWebImage provides several interfaces for loading images: from the simple UIImageView category to the advanced manager with custom processing.
sd_setImage is the primary method for loading an image into UIImageView. It accepts a URL, placeholder, and optional parameters through Options and Context. All Completion Handlers are executed on the main thread.
let imageView = UIImageView()
imageView.sd_setImage(
with: URL(string: "https://example.com/photo.jpg"),
placeholderImage: UIImage(named: "placeholder"),
options: [.progressiveLoad, .retryFailed],
context: [.imageThumbnailPixelSize : CGSize(width: 300, height: 300)]
)
The method returns an SDWebImageToken (operation) that can be cancelled if needed. Internally, sd_setImage calls SDWebImageManager.load, passing the ImageView as the Target for automatic image setting.
SDWebImage supports Transformer — a protocol with a single method transformedImage. Built-in transformations include: circle, rounded corners, color filter overlay, and resizing. Transformations can be combined using the && operator.
let transformer = SDImageResizingTransformer(
size: CGSize(width: 200, height: 200),
scaleMode: .aspectFill
)
let roundedTransformer = SDImageRoundCornerTransformer(
radius: 16,
corners: .allCorners,
borderWidth: 0
)
imageView.sd_setImage(
with: url,
placeholderImage: placeholder,
context: [.imageTransformer : transformer && roundedTransformer]
)
The library provides WebImage — a View component for SwiftUI with support for placeholder, progress indicator, and error handling. The component automatically subscribes to the View lifecycle and cancels loading when it disappears.
struct CachedImageView: View {
let url: URL
var body: some View {
WebImage(url: url) { phase in
if let image = phase.image {
image.resizable()
} else if phase.error {
Color.red
} else {
ProgressView()
}
}
}
}
SDWebImage provides a flexible transformation system through the SDImageTransformer protocol. Transformations are applied after decoding but before caching — the transformation result is stored on disk under a new key, preventing re-application on subsequent requests.
Built-in transformations include: SDImageResizingTransformer (resizing with mode), SDImageRoundCornerTransformer (rounded corners with optional border), SDImageFlipTransformer (mirroring), and SDImageFilterTransformer (CoreImage filters). Combining is done via the && operator, creating a processing chain.
For custom transformations, simply implement the SDImageTransformer protocol with the transformedImageWithImage:forKey: method. The transformation key is automatically appended to the cache key, preventing collisions between different versions of the same image.
On the iOS platform, the main competitors to SDWebImage are Kingfisher (pure Swift) and Nuke. The choice between SDWebImage and Kingfisher is often determined by the project language and the required functionality.
| Feature | SDWebImage | Kingfisher |
|---|---|---|
| Language | Objective-C + Swift API | Swift (100%) |
| SwiftUI | WebImage View | KFImage View |
| GIF | Yes (built-in) | Yes (built-in) |
| WebP | Yes (plugin) | Yes (built-in) |
| Progressive Loading | Yes (with plugin) | Yes |
| Framework Size | ~1.2 MB | ~900 KB |
| Cache | Memory + Disk | Memory + Disk |
| CocoaPods Support | Yes | Yes |
SDWebImage remains the preferred choice for Objective-C projects or hybrid projects. Kingfisher is better suited for pure Swift projects thanks to type safety and native Swift syntax. Both libraries have similar caching architecture and performance.
SDWebImage can be integrated via Swift Package Manager, CocoaPods, or Carthage. The library is split into modules: core (SDWebImage), Coder (additional formats), and MapKit (for MKAnnotationView).
// Swift Package Manager (Package.swift)
dependencies: [
.package(
url: "https://github.com/SDWebImage/SDWebImage.git",
from: "5.19.0"
)
]
// CocoaPods (Podfile)
pod 'SDWebImage', '~> 5.19.0'
// Plugins for WebP and SVG:
pod 'SDWebImageWebPCoder'
pod 'SDWebImageSVGCoder'
After installation, the library is ready to use without additional configuration. For cache customization, create an instance of SDImageCache with a unique namespace, and pass it to SDWebImageManager during initialization. Global configuration is done through SDWebImageManager.shared.
// Cache Customization
let config = SDImageCacheConfig()
config.maxDiskAge = 14 * 86400 // 14 days instead of 7
config.maxDiskSize = 500 * 1024 * 1024 // 500 MB
config.shouldCacheImagesInMemory = .true
let cache = SDImageCache(
namespace: "custom",
diskCacheDirectory: FileManager.default.urls(
for: .cachesDirectory,
in: .userDomainMask
).first?.appendingPathComponent("custom_cache"),
config: config
)
SDWebImageManager.sharedImageCache = cache
Frequently Asked Questions
SDWebImage is a library for asynchronous image loading on iOS and macOS. It solves the problems of caching, decoding, transforming, and displaying images from the network, freeing the developer from manual thread and memory management.
In the cellForRowAt method, use sd_setImage with a URL and placeholder. The library automatically cancels the previous request when the cell is reused. For smooth scrolling, specify the .progressiveLoad option and configure the thumbnail size through the context.
SDWebImage is written in Objective-C with a Swift wrapper, while Kingfisher is written in pure Swift. SDWebImage has a larger plugin ecosystem (WebP, SVG, MapKit). Kingfisher provides better type safety and Swift Concurrency integration.
Install the SDWebImageWebPCoder plugin via CocoaPods or SPM. Register the coder by calling SDImageWebPCoder.shared in AppDelegate. After registration, the library automatically detects the format and decodes WebP.
Call SDImageCache.shared.clearMemory() for memory and SDImageCache.shared.clearDisk() for disk. To clear only outdated files, use clearDisk(completion:) with TTL checking. The calculateSizeWithCompletionBlock method returns the current cache size.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also