Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jun 11, 2019

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.