I have empty url string from my image. I keep my url string image in firestore. But sometimes it happens that there is no image and I need to make a check and return an empty image.
When I load my view I get an error nil
. Because my variable in firestore is empty.
It's my code:
guard let dataLogoImage = try? Data(contentsOf: URL(string: self.hall!.studioHallLogo)!) else { return }
And later I apply dataLogoImage
to variable tempLogoImage
.
self.tempLogoImage = UIImage(data: dataLogoImage)
How do I do a check Data
or empty url string and avoid nil
?
David is right. So here's a sample of URLSession.dataTask
usage. This should work for you.
if let urlString = self.hall?.studioHallLogo,
let url = URL(string: urlString) {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
// execute on main thread
DispatchQueue.main.async {
self.tempLogoImage = UIImage(data: data)
}
}
task.resume()
}
As you can see, we're unwrapping your optional stuff safely, such as self.hall?.studioHallLogo
, and the creation of your URL
object. :) Soon you'll prolly need a library to handle image loading better and with caching. I would love to suggest: Kingfisher
I hope this helps. Good luck.