Last active
November 27, 2019 23:59
-
-
Save Bradysm/16fa40e9b14e47ebc596d79e007341f2 to your computer and use it in GitHub Desktop.
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
/** | |
Class used to load URL images asynchronously | |
*/ | |
final class ImageLoader: ObservableObject { | |
@Published public var imageData:Data // data that will get published when loaded | |
init(url imageUrl: String) { | |
self.imageData = Data() // assign the value | |
// call the API and try to get the data | |
guard let url = URL(string: imageUrl) else { return } // craete the URL struct | |
URLSession.shared.dataTask(with: url) { (data, res, err) in | |
if let unwrappedData = data { | |
DispatchQueue.main.async { | |
self.imageData = unwrappedData | |
} | |
} | |
}.resume() | |
} | |
} | |
/** | |
SwiftUI view that loads an image from a URL asynchronously | |
If the image is not available, then the default image is set to Image Unvavailable | |
otherwise, the image is updated to contain the image loaded from the URL | |
*/ | |
struct URLImage: View { | |
@ObservedObject var loader: ImageLoader | |
init(imageUrl: String) { | |
loader = ImageLoader(url: imageUrl) | |
} | |
var body: some View { | |
Image(uiImage: (loader.imageData.isEmpty ? UIImage(named: "ImageUnavailable")! : UIImage(data: loader.imageData) ?? UIImage(contentsOfFile: "ImageUnavailable")!)) | |
.resizable() | |
.aspectRatio(contentMode: .fit) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment