如何安全地打开我在Firebase中从我的数据库调用的URL这个可选项?

时间:2017-07-03 12:49:03

标签: ios swift url firebase optional

这是屏幕截图,因为你可以看到它显示错误,因为我强制解包并且一些网址是空的:

Image

如何安全地打开此网址,以便我不必强制解包?

代码:

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
}

3 个答案:

答案 0 :(得分:2)

检查字符串后,您应该检查URL本身的值。这两个字符串都会以这种方式安全地解开。

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

答案 1 :(得分:0)

你可以试试这个

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

答案 2 :(得分:-1)

使用下面的代码也可以解决您在纳秒内加载图像的问题。试试这个

extension UIImageView {
public func imageFromUrl(urlString: String) {
    if let url = NSURL(string: urlString) {
        let request = NSURLRequest(url: url as URL)
        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) { (response: URLResponse?, data: Data?, error: Error?) -> Void in
            if let imageData = data as NSData? {
                self.image = UIImage(data: imageData as Data)
            }
        }
    }
  }
}

使用

if players[indexPath.row].imageUrl != "" && players[indexPath.row].imageUrl != nil {
   cell.profileImage.imageFromUrl(urlString: players[indexPath.row].imageUrl)
}
  

希望这会帮助您解决问题