Last active
April 11, 2017 05:55
-
-
Save tomaskraina/ef2c84e568f07491fe4d7f0480b65602 to your computer and use it in GitHub Desktop.
How to using Kingfisher (https://github.com/tomaskraina/Kingfisher/tree/downloader-delegate-will-start) with AlamofireNetworkActivityIndicator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Kingfisher | |
import Alamofire | |
private var kingfisherDownloadDelegate = KingfisherDownloadDelegate() | |
class KingfisherDownloadDelegate: ImageDownloaderDelegate { | |
private var ongoingRequests: [URL] = [] | |
private let lock = NSLock() | |
func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) { | |
precondition(Thread.isMainThread) | |
// For some mysterious reason, the delegate method `didDownload` gets called more times | |
// then `willDownloadImageForURL`. Therefore, we need to keep track of the requested URLs | |
// in order to post just the right number of `Task.DidComplete` notifications. | |
lock.lock() | |
ongoingRequests.append(url) | |
lock.unlock() | |
NotificationCenter.default.post(name: Notification.Name.Task.DidResume, object: nil) | |
} | |
func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) { | |
DispatchQueue.main.async { | |
self.lock.lock() | |
if let index = self.ongoingRequests.index(of: url) { | |
self.ongoingRequests.remove(at: index) | |
NotificationCenter.default.post(name: Notification.Name.Task.DidComplete, object: nil) | |
} else { | |
print("Request not found, url=\(url.absoluteString)") | |
} | |
self.lock.unlock() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment