I'm currently trying to find a way to save an image from AsyncImage so I can cache it right away (without using a separate image retrieval process).
This is my code for AsyncImage and the Extension on View I'm using to try to save it.
AsyncImage(url: asyncUrl) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image
.resizable()
.scaledToFit()
urlImageModel.image = image.snapshot()
case .failure:
Image(uiImage: UrlImageView.defaultImage!)
.resizable()
.scaledToFit()
@unknown default:
Image(uiImage: UrlImageView.defaultImage!)
.resizable()
.scaledToFit()
}
}
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
Unfortunately, when I put the code in case .success to save the image in my urlImageModel, it gives this error:
Type () cannot conform to View in reference to the image closure.
Any ideas on how to save the image from within AsyncImage would be appreciated!