I am creating a simple Photo library app based on a users Photo library. I have a LibraryView that displays all the photos, and when clicking on a Photo a DetailView loads that should display information from the photo. The issue I am facing is that @Published vars in my DetailView's viewModel are being set to nil.
In the LibraryView I create a AssetViewModel for each photo by passing in the PHAsset object to the initializer:
ForEach(assets) { asset in
NavigationLink(destination: DetailView(asset: AssetViewModel(asset: asset))) {
// Thumbnail image
}
}
This AssetViewModel is a ObservedObject and during the init I only set it's asset, which is a PHAsset.
@Published private var asset: PHAsset
init(asset: PHAsset) {
self.asset = asset
}
In my DetailView I call a load function in my AssetViewModel with the onAppear modifier. In this load function, I call some other funcitons to setup some variables of the ViewModel such as it's image. The function that fetches the image has an escaping closure. Once this is finished, I update the image var of my AssetViewModel, which is parked as @Published. See below:
func load() {
let imageSize = CGSize(width: 200, height: 200)
setImage(targetSize: imageSize)
// Some other stuff as well
}
// The image of the asset
@Published private (set) var image: UIImage?
// Function that fetches and sets the image of the asset
private func setImage(targetSize: CGSize) {
asset.imageForAsset(targetSize: targetSize) { (image) in
DispatchQueue.main.async {
self.image = image
}
}
}
Now the problem is that if I click on a photo from my LibraryView, the new DetailView slides in, and it shows the image, but after a fraction of a second the image is gone and the image var in my AssetViewModel is nil. I have no clue why this is happening..