Last active
August 16, 2021 06:28
-
-
Save ivanbruel/b2838f62cb281bd974ec9c9c121c6cbe to your computer and use it in GitHub Desktop.
Basic NetworkImage support for SwiftUI via Kingfisher
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!