Skip to content

Instantly share code, notes, and snippets.

@tomaskraina
Last active April 11, 2017 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomaskraina/ef2c84e568f07491fe4d7f0480b65602 to your computer and use it in GitHub Desktop.
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
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