Force reload Image when url changes SwiftUI

765 Views Asked by At

New (to swiftui), I would like to display an image(refresh the view) as soon the url is ready .Apparently State var isn t enough . It seems like .onReceive and a publisher might help but i iam helpless . NB : i use KingFisher but it seems to be the same case for any loader .The situation seems special (url not ready when view created) but this is a more general topic: for example when requests are sync and profile photo needs to be updated when the other user changes it .

Edit: After some more tests, it appears that view is updated if ,for example , we use a dispachQueue to postpone for one second and then try to update . It is not updated when retrieving the value directly with firebase onAppear

import SwiftUI
import Firebase
import Kingfisher


struct Test4: View {

    @State private var mProfilePhotoUrl: URL = URL(string:"0")!
 
 var body: some View {
    
 VStack(alignment: .center,spacing : 0){
           
           KFImage(mProfilePhotoUrl)
      
  }.onAppear(){
        setUpProfileElements()
       }
     
    }
    
    private func setUpProfileElements(){

    //    FirebaseRequest -> mProfilePhotoUrl = URL(string: User.profilePhoto)
     
    }
    
}
1

There are 1 best solutions below

3
it75 On BEST ANSWER

This is jnpdx Answer ! I dont know the reason , if it was too close from displaying, but view wouldn t update with the firebase request onAppear, using id foreced the refresh.

struct Test4: View {

    @State private var mProfilePhotoUrl: URL = URL(string:"0")!
    *@State private var ID = 0*

 var body: some View {
    
 VStack(alignment: .center,spacing : 0){
           
           KFImage(mProfilePhotoUrl)*.id(ID)*
      
  }.onAppear(){
        setUpProfileElements()
       }
     
    }
    
    private func setUpProfileElements(){

    //    FirebaseRequest -> mProfilePhotoUrl = URL(string: User.profilePhoto)
     //                    *-> self.ID += 1*
    }
    
}