SDWebImage: What It Is, Key Concepts, and UIImageView

Author: IT Sectr Published: 2026-05-05 Reading time: 8 min

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 iOS with support for caching, animations, and transformations.
  • SDWebImageManager is the central class that coordinates image loading, decoding, and caching.
  • Disk Cache saves images to storage, enabling offline loading on subsequent visits.
  • WebP and GIF are supported through the SDImageWebPCoder and SDImageGIFCoder plugins.
  • SwiftUI — the library provides the WebImage View component for declarative image loading.

What is SDWebImage?

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.

How SDWebImage Works: Manager and Cache

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.

Loading Process

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.

  • Memory Cache — O(1) lookup, stores UIImage with a configurable memory limit
  • Disk Cache — reads from the file system, stores compressed data
  • NSURLSession — loading with HTTP/2 support and configurable timeout

UIImageView Category

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.

Core SDWebImage Classes

The SDWebImage architecture is divided into several modules with clear responsibility zones. Each class solves one task — from loading to display.

SDWebImageManager

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

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

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 Caching Architecture

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.

LevelStorage TypeContentLimit
Memory CacheNSCache (NSDictionary)UIImage (decoded Bitmap)Until memory warning
Disk CacheFile systemNSData (JPEG/PNG/WebP)7 days TTL (configurable)
Auto Purge CacheMemory + DiskCombined framework cacheConfigurable 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 Usage Examples in Swift

SDWebImage provides several interfaces for loading images: from the simple UIImageView category to the advanced manager with custom processing.

Basic UIImageView Loading

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.

swift
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.

Loading with Custom Transformation

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.

swift
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]
)

Using with SwiftUI

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.

swift
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()
            }
        }
    }
}

Image Transformations in SDWebImage

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.

SDWebImage vs Kingfisher Comparison

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.

FeatureSDWebImageKingfisher
LanguageObjective-C + Swift APISwift (100%)
SwiftUIWebImage ViewKFImage View
GIFYes (built-in)Yes (built-in)
WebPYes (plugin)Yes (built-in)
Progressive LoadingYes (with plugin)Yes
Framework Size~1.2 MB~900 KB
CacheMemory + DiskMemory + Disk
CocoaPods SupportYesYes

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.

Setting Up SDWebImage in an iOS Project

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
// 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.

swift
// 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

What is SDWebImage and what problems does it solve?

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.

How to use SDWebImage with UITableView?

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.

How is SDWebImage different from Kingfisher?

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.

How to add WebP support to SDWebImage?

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.

How to clear the SDWebImage cache programmatically?

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

  • SDWebImage is the de facto standard for image loading on iOS with over 25,000 stars on GitHub.
  • Two-level cache (Memory + Disk) ensures instant loading of repeated images and offline access.
  • Progressive loading and support for GIF, WebP, SVG make the library a universal solution for any format.
  • SDWebImageManager provides a unified facade for loading with the ability to customize each component.
  • WebImage for SwiftUI allows loading images in a declarative style with full state handling.
  • Transformations (resize, rounding, color) are combined using the && operator and are applied before caching.
  • Objective-C compatibility makes SDWebImage accessible to legacy projects without migrating to Swift.

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.

Discuss the project

Read also