Say Goodbye to SDWebImage in SwiftUI – Now with Image Caching!
Muhammad Danish Qureshi
iOS Engineer | UIKit | Swift | SwiftUI | MVVMR | Objective-C | SDK
Hey iOS Developers! In my previous post, I shared how AsyncImage in SwiftUI can replace third-party libraries like SDWebImage for loading images from the web. Many of you rightly pointed out that SDWebImage has a key advantage: image caching. Well, guess what? We can now achieve the same caching functionality natively in SwiftUI! ??
Here’s how I implemented image caching using NSCache and AsyncImage:
// Wrapper class to store Image in NSCache
class ImageWrapper: NSObject {
let image: Image
init(image: Image) {
self.image = image
}
}
// NSCache to store ImageWrapper objects
let imageCache = NSCache<NSString, ImageWrapper>()
struct CustomImageViewWithAsync: View {
private let imageUrl = "https://credo.academy/[email protected]"
var body: some View {
if let cachedImageWrapper = imageCache.object(forKey: imageUrl as NSString) {
// If cached, use the cached image
cachedImageWrapper.image
.imageModifier()
.frame(width: 250, height: 250)
.border(Color.gray)
} else {
AsyncImage(url: URL(string: imageUrl)) { phase in
if let image = phase.image {
image
.imageModifier()
.onAppear {
// Wrap the Image in ImageWrapper and cache it
let imageWrapper = ImageWrapper(image: image)
imageCache.setObject(imageWrapper, forKey: imageUrl as NSString)
}
} else if phase.error != nil {
Image(systemName: "ant.circle.fill").iconModifier()
} else {
Image(systemName: "photo.circle.fill").iconModifier()
}
}
.frame(width: 250, height: 250)
.border(Color.gray)
}
}
}
// Modifiers for Image
extension Image {
func imageModifier() -> some View {
self
.resizable()
.scaledToFit()
.clipShape(Circle())
.shadow(radius: 10)
}
func iconModifier() -> some View {
self
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
.foregroundColor(.gray)
}
}
How It Works:
领英推荐
Why This Matters:
? Native Solution: No need for third-party libraries like SDWebImage. ? Efficient Caching: Images are cached in memory, reducing redundant network requests. ? SwiftUI-First: Fully integrated with SwiftUI’s declarative syntax and state management.
With this approach, we can now fully replace SDWebImage in SwiftUI projects while retaining the benefits of image caching. ??
What do you think? Are you ready to make the switch to a fully native solution? Let me know your thoughts in the comments! ??
#SwiftUI #iOSDevelopment #AsyncImage #ImageCaching #Swift #AppleDeveloper #MDanishPK