Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I safely unwrap this URL optional which i call from my database in Firebase?

This is the screen shot as you can see it shows error as I forced unwrapped and some urls are empty:

Image

How can I safely unwrap this URL so I don't have to force unwrap ?

Code:

func tableView    (_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int 
{
        return players.count
    }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: 
Reusable.reuseIdForMain) as! CustomCell
        cell.nameLabel.text = players[indexPath.row].name
        cell.otherInfo.text = players[indexPath.row].otherInfo


if let url = players[indexPath.row].imageUrl{
            cell.profileImage.load.request(with: URL(string:url)!)

    }


    return cell
}
like image 917
Big Boss Avatar asked Jan 01 '26 10:01

Big Boss


2 Answers

You should check for the value of the URL itself after checking the string. Both strings will be safely unwrapped this way.

if let urlString = players[indexPath.row].imageUrl,
    let url = URL(string: urlString) {
    cell.profileImage.load.request(with: url)
}
like image 89
Tamás Sengel Avatar answered Jan 03 '26 02:01

Tamás Sengel


You can try this

if let imageUrl = players[indexPath.row].imageUrl as? String{
     let url = URL(string: imageUrl)
     if let url = url {
            cell.profileImage.load.request(with: url)
     }
  }
like image 30
DionizB Avatar answered Jan 03 '26 02:01

DionizB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!