Skip to content

Instantly share code, notes, and snippets.

@ivanbruel
Last active August 16, 2021 06:28
Show Gist options
  • Save ivanbruel/b2838f62cb281bd974ec9c9c121c6cbe to your computer and use it in GitHub Desktop.
Save ivanbruel/b2838f62cb281bd974ec9c9c121c6cbe to your computer and use it in GitHub Desktop.
Basic NetworkImage support for SwiftUI via Kingfisher
import SwiftUI
import Kingfisher
import UIKit
public struct NetworkImage: SwiftUI.View {
// swiftlint:disable:next redundant_optional_initialization
@State private var image: UIImage? = nil
public let imageURL: URL?
public let placeholderImage: UIImage
public let animation: Animation = .basic()
public var body: some SwiftUI.View {
Image(uiImage: image ?? placeholderImage)
.resizable()
.onAppear(perform: loadImage)
.transition(.opacity)
.id(image ?? placeholderImage)
}
private func loadImage() {
guard let imageURL = imageURL, image == nil else { return }
KingfisherManager.shared.retrieveImage(with: imageURL) { result in
switch result {
case .success(let imageResult):
withAnimation(self.animation) {
self.image = imageResult.image
}
case .failure:
break
}
}
}
}
#if DEBUG
// swiftlint:disable:next type_name
struct NetworkImage_Previews: PreviewProvider {
static var previews: some SwiftUI.View {
NetworkImage(imageURL: URL(string: "https://www.apple.com/favicon.ico")!,
placeholderImage: UIImage(systemName: "bookmark")!)
}
}
#endif
@DazChong
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment