I am fetching images from Firebase storage, if there is no image on firebase, I want to show thumbnail,
Thats where I get the error
if let error = error {
Swift.print(error)
}
Here is my thumbnail
Image("shoePlaceHolder")
.resizable()
.aspectRatio(contentMode: .fit)
Here is the complete code
func getFullImageURL() {
let storage = Storage.storage()
let storagePath = "gs://on-switch.appspot.com/main/(season)/"
let storageRef = storage.reference(forURL: storagePath)
let formattedImageURL = imageURL.absoluteString.replacingOccurrences(of: "file:///", with: "")
let ref = storageRef.child(formattedImageURL)
ref.downloadURL { url, error in
DispatchQueue.main.async {
if let error = error {
Swift.print(error)
} else if let url = url {
fullImageURL = url
} else {
Swift.print("No url and no error")
}
}
}
}
@ViewBuilder
var content: some View {
VStack {
VStack {
headerView()
HStack {
AsyncImage(url: $fullImageURL.wrappedValue) { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
} placeholder: {
Image("shoePlaceHolder")
.resizable()
.aspectRatio(contentMode: .fit)
}.frame(width: 260, height: 180)
.onAppear(perform: getFullImageURL)
VStack(alignment: .leading) {
titleView()
subtitleView()
}
Spacer()
}
}
.padding()
OnDivider()
.padding(.horizontal)
SectionView(leadingView: {
Text("(variants.count) variants")
.secondaryText()
}, trailingView: {
Image(systemName: "rectangle.expand.vertical")
.foregroundColor(Color(.secondaryLabel))
}).padding()
}
4
Answers
Since no image was shown as an error, you just need to focus on the error. Something like:
This works for me
If you want to use a custom image, make sure
shoePlaceHolder
is added to the projectAssets
..
You can use a struct instead of a @State, @Published or whatever you’re using to store fullImageURL.
Something like:
So you can simply inform the URL and the error as needed:
That way you can display a different placeholder in case of error or no placeholder at all, depending or your needs:
You have to use this line to invoke the listener for
fullImageURL
and the complete code will look like this: