Search code examples
macosswiftuiview

How to get AsyncImage to update the View with changing image


I'm using an observable object to cause the update of a view - an image file is being updated every second by a driver. But the actual image is not updated, only the opacity property - I was just using opacity to see the change. I was expecting the whole view including the image itself to be updated with a change in the observed object.

Here is the code:

import SwiftUI

struct StreamingImageView: View {
    var filePath = URL(string: "file:/Users/\(NSUserName())/Library/Containers/GB.IndigoPolarAlignAid/Data/img_01.jpg")
    @ObservedObject var monitor: FileMonitor
    
    init(){
        print("StreamingImageView: \(filePath!)")
        monitor = FileMonitor(filePath: filePath!)
    }
    
    var body: some View {
        GeometryReader { geometry in
            AsyncImage(url: filePath)
                .opacity(Double(monitor.fileUpdateCount)/10.0)
            Text("count \(monitor.fileUpdateCount) \(filePath!)")
        }
    }
}

Solution

  • The answer was provided by @jnpdx - in the discussion above - who suggested adding a unique id property - I used the monitor.fileUpdateCount to do this and get an updated display with refreshed jpg as I wanted. Here is minimal code that works:

    import SwiftUI
    
    let filePath = URL(string: "file:/Users/\(NSUserName())/Library/Containers/GB.IndigoPolarAlignAid/Data/img_01.jpg")
    
    struct StreamingImageView: View {
        @ObservedObject var monitor: FileMonitor = FileMonitor(filePath: filePath!)
        var id: Int = 0
    
        var body: some View {
                AsyncImage(url: monitor.filePath)
                        .id(monitor.fileUpdateCount)
    }