Say Goodbye to SDWebImage in SwiftUI – Now with Image Caching!

Say Goodbye to SDWebImage in SwiftUI – Now with Image Caching!

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:

  1. Caching Mechanism: Using NSCache, we store the loaded Image in a wrapper class (ImageWrapper). This ensures that once an image is loaded, it’s cached and reused on subsequent loads.
  2. AsyncImage Integration: The AsyncImage view handles loading, success, and error states seamlessly, while the caching logic ensures optimal performance.
  3. No Third-Party Libraries: This solution is entirely native to SwiftUI and doesn’t rely on external dependencies.

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

要查看或添加评论,请登录

Muhammad Danish Qureshi的更多文章

社区洞察

其他会员也浏览了