Skip to content

Instantly share code, notes, and snippets.

@marcosgriselli
Created August 30, 2017 14:44
Show Gist options
  • Save marcosgriselli/8107b2afa7368cf1b996304f96d09800 to your computer and use it in GitHub Desktop.
Save marcosgriselli/8107b2afa7368cf1b996304f96d09800 to your computer and use it in GitHub Desktop.
Bridge between Kingfisher and UIImageView for easy swapping between 3rd party image download libraries
//
// UIImageView+URL.swift
// marcosgriselli
//
// Created by Marcos Griselli.
// Copyright © 2017 marcosgriselli. All rights reserved.
//
import Kingfisher
public enum ImageAnimation {
case flipFromLeft
case flipFromRight
case fade
/// Kingfisher transition. This keeps all animation code together rather than distributed in the codebase.
/// Makes it easier to hadle it and modify it in the future
///
/// - Returns: current third party library animator. Currently: ImageTransition
func convert(withDuration duration: TimeInterval) -> ImageTransition {
switch self {
case .flipFromLeft:
return ImageTransition.flipFromLeft(duration)
case .flipFromRight:
return ImageTransition.flipFromRight(duration)
case .fade:
return ImageTransition.fade(duration)
}
}
}
// MARK: - UIImageView image downloader from URL's
extension UIImageView {
func setImage(fromURL url: URL) {
kf.setImage(with: url)
}
func setImage(fromURL url: URL,
withPlaceholderImage placeholder: UIImage?,
animation: ImageAnimation? = nil,
duration: TimeInterval? = 0,
completion: CompletionHandler? = nil) {
var options: KingfisherOptionsInfo? = nil
if let animation = animation {
options?.append(.transition(animation.convert(withDuration: duration ?? 0.2)))
}
kf.setImage(with: url,
placeholder: placeholder,
options: options,
progressBlock: nil,
completionHandler: completion)
}
func setImage(fromString string: String?) {
guard let string = string, let url = URL(string: string) else { return }
setImage(fromURL: url)
}
func setImage(fromString string: String?, completion: @escaping CompletionHandler) {
guard let string = string, let url = URL(string: string) else { return }
setImage(fromURL: url,
withPlaceholderImage: nil,
animation: nil,
duration: nil,
completion: completion)
}
func cancelDownload() {
kf.cancelDownloadTask()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment