如何利用SDWebImage预加载完成回调隐藏CollectionView加载界面?
Solution: Hide Loading View After SDWebImage Prefetch Completes
Hey there! The key here is to use the completion block version of SDWebImagePrefetcher's prefetch method, which lets you run code once all image requests (successful or not) have finished processing. Here's how to implement this properly:
Step 1: Prepare Your Loading View
First, make sure you have your loading interface set up (e.g., a UIActivityIndicatorView or a custom overlay view). Show it when your view loads:
// Assume you have an IBOutlet for your loading view @IBOutlet weak var loadingOverlay: UIView! override func viewDidLoad() { super.viewDidLoad() // Show loading overlay first loadingOverlay.isHidden = false // Your URL array let urls: [URL] = [ URL(string: "https://trialwebsite.com/image1.png")!, URL(string: "https://trialwebsite.com/image2.png")!, URL(string: "https://trialwebsite.com/image3.png")! ] // Run prefetch with completion callback startImagePrefetch(for: urls) }
Step 2: Implement Prefetch with Completion Callback
Use prefetchURLs(_:progress:completed:) instead of the basic prefetchURLs method. This gives you access to a completion block that triggers once all requests are done. Important: Always update UI on the main thread!
private func startImagePrefetch(for urls: [URL]) { SDWebImagePrefetcher.shared.prefetchURLs(urls, progress: { (completedCount, totalCount) in // Optional: Update progress if you want (e.g., progress bar) print("Prefetched \(completedCount)/\(totalCount) images") }, completed: { (totalPrefetched, totalSkipped) in // All requests are finished - hide loading overlay on main thread DispatchQueue.main.async { self.loadingOverlay.isHidden = true // Optional: Reload your CollectionView here if needed self.collectionView.reloadData() } print("Prefetch done! Successfully loaded: \(totalPrefetched), Skipped (already cached): \(totalSkipped)") }) }
Key Notes:
- The
completedblock runs after every image in your URL array has been processed—whether it was successfully cached, skipped (already existed in cache), or failed to load. This is exactly what you need to trigger hiding your loading interface. - Wrapping the UI update in
DispatchQueue.main.asyncis critical because SDWebImage runs its callbacks on a background thread by default. Updating UI from a non-main thread can cause crashes or unexpected behavior. - If you want to handle success/failure separately (e.g., only hide the loader if all images succeeded), you can track failures in the progress block, but for most cases, waiting for all requests to finish (regardless of outcome) is the right approach.
内容的提问来源于stack exchange,提问作者MattBlack
相关产品推荐
相关产品推荐

