2

I am loading images from URLs with the KFImage of the Kingfisher Library. There is the probability that some URLs are invalid. So Kingfisher will not be able to load an image from this url. In this case i would like to collapse the KFImage.

HStack(alignment: .top) {
    KFImage(someUrl)
    Text("some Text")
}

In this case the KFImage takes all place it can take. I found a solution with the onSuccess Listener of KFImage.

KFImage(url)
    .onSuccess { _ in
       self.canLoadImage = true
    }
    .forceRefresh()
    .resizable()
    .aspectRatio(contentMode: .fill)
    .cornerRadius(20)
    .clipped()
    .frame(width: canLoadImage ? 150 : 0)
}

In this case the Image collapses and on Failure but has a width on Success. But this solution seems too complex to be the best solution possible. Since i am quiet new iOS development my ideas for better solutions are quiet limited.

Larme
  • 24,190
  • 6
  • 51
  • 81
tscheppe
  • 588
  • 5
  • 18
  • Is your solution not working? – Timmy Aug 22 '22 at 11:54
  • @Timmy my solution is working. but it seems unnecassary complex to me. and i wonder why i cannot just set a maxWidth to KFImage for example. When i set maxWidth it always takes maxWidth. probabyl there is another nice solution i did not come up with so fare. – tscheppe Aug 22 '22 at 11:57

2 Answers2

2

You can completely remove the image from the View using an if statement:

if canLoadImage {
    KFImage(url)
        .onSuccess { _ in
            self.canLoadImage = true
        }
        .forceRefresh()
        .resizable()
        .aspectRatio(contentMode: .fill)
        .cornerRadius(20)
        .clipped()
        .frame(width: 150)
}
Timmy
  • 4,098
  • 2
  • 14
  • 34
2

Not really clear what do you want, but if you want to remove it on failure completely (instead of decrease some size) just make it conditional, like

@State private var imageVisible = true

...

HStack(alignment: .top) {
    if imageVisible {
      KFImage(someUrl)
        .onFailure { _ in
            imageVisible = false
        }
    }
    Text("some Text")
}
Asperi
  • 228,894
  • 20
  • 464
  • 690