TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftUI: Setting @Published property in ViewModel weird behaviour

Forums > SwiftUI

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..

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.