阅读可选的链接问题?

时间:2018-07-05 15:40:31

标签: ios swift optional

我遇到了错误:

  

严重错误:解开Optional值时意外发现nil。

DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
    let imageString = self.thumblist1[indexPath.item]
    let imageUrl = URL(string: imageString)
    let imageData = try? Data(contentsOf: imageUrl!)
    DispatchQueue.main.async {
        if (imageData != nil)
        {
            cell2?.verticalImageView.image = UIImage(data: imageData!)
        }
    }
}

return cell2!

1 个答案:

答案 0 :(得分:2)

在致电imageUrl之前检查您的image是否为零:

DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {

let imageString = self.thumblist1[indexPath.item]
if let imageUrl = URL(string: imageString) {
    let imageData = try? Data(contentsOf: imageUrl)
    DispatchQueue.main.async {
        if (imageData != nil)
        {
            cell2?.verticalImageView.image = UIImage(data: imageData!)
        }
    }
}

}
 return cell2!
 }