This is pretty slick. Here’s the view model I came up with for displaying an image from a ParseFile. Sharing in hope this might help others or let me know if there’s a better way to accomplish this:
class ParsePhotoPublisher: ObservableObject {
var parseFile: ParseFile? {
didSet {
Task {
await fetchImage()
}
}
}
@Published var image: UIImage = UIImage(systemName: "arrow.down.to.line")!
@Published var downloaded = false
func fetchImage() async {
Task{
do {
let fetchedFile = try await parseFile?.fetch()
if let localURL = fetchedFile?.localURL, let uiImage = UIImage(contentsOfFile: localURL.relativePath){
Task { @MainActor in
image = uiImage
downloaded = true
}
}
}
catch {
print("unable to fetch file")
}
}
}
}
struct PhotoView: View {
let photoFile: ParseFile
@StateObject var imageViewModel = ParsePhotoPublisher()
var body: some View {
VStack{
if self.imageViewModel.downloaded {
Image(uiImage: self.imageViewModel.image)
.resizable()
.scaledToFill()
.shadow(radius: 3)
.cornerRadius(3.0)
}else {
HStack{
Spacer()
ProgressView()
Spacer()
}
}
}
.frame(width: UIScreen.main.bounds.size.width - 150, height: UIScreen.main.bounds.size.width - 150, alignment: .leading)
.onAppear{
self.imageViewModel.parseFile = photoFile
}
}
}