gpt4 book ai didi

swift - 具有真实数据的 UIImage init 返回 nil

转载 作者:行者123 更新时间:2023-11-28 08:25:40 25 4
gpt4 key购买 nike

美好的一天!这让我很生气,因为我不明白发生了什么。
我有 2 个具有类似逻辑的 TableViewController。
我使用 1 个数据模型。
此模型包含用户信息,每个实体始终有一张照片。

为了初始化它,我使用下面的代码:

var partnerPhoto: UIImage? = nil
if let imageData = partners[indexPath.item].userPhoto {
partnerPhoto = UIImage(data: imageData as! Data)
}

在调试中 partners[indexPath.item].userPhoto 有真实数据,甚至 imageData 显示 4213 字节。
但是,应用程序崩溃并出现典型错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

编辑:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if dialogs[indexPath.item].fromID == profileID {
let cell = tableView.dequeueReusableCell(withIdentifier: "dialogMeCell", for: indexPath) as! CellForDialogMe
var partnerPhoto: UIImage? = nil
if let imageData = partners[indexPath.item].userPhoto {
partnerPhoto = UIImage(data: imageData as! Data)
}
cell.fillWithContent(partnerPhoto: partnerPhoto!, selfPhoto: profilePhoto!)
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "dialogHimCell", for: indexPath) as! CellForDialogHim
var partnerPhoto: UIImage? = nil
if let imageData = partners[indexPath.item].userPhoto {
partnerPhoto = UIImage(data: imageData as! Data)
}
cell.fillWithContent(partnerPhoto: partnerPhoto!)
return cell
}

解决方案:事实上我还没有找到这个问题的具体解决方案,我只是将一些逻辑从模型转移到 View Controller 。在模型中,我确实从 URL 加载到数据。现在我在 ViewController 中正确地完成它并且它工作完美,但它很奇怪,对我来说非常奇怪,因为我只是做了 cmd-x cmd-v。

最佳答案

在范围之前转换您的 imageData:

if let imageData = partners[indexPath.row].userPhoto as? Data {
partnerPhoto = UIImage(data: imageData)
} else {
partnerPhoto = UIImage() //just to prevent the crash
debugPrint("imageData is incorrect")
//You can set here some kind of placeholder image instead of broken imageData here like UIImage(named: "placeholder.png")
}
cell.fillWithContent(partnerPhoto: partnerPhoto)
return cell

此外,如果您能提供更多详细信息 - profilePhoto 的初始化方式和时间以及cell.fillWithContent(partnerPhoto: partnerPhoto!, selfPhoto: profilePhoto!) 代码。

此外,您还可以在 cell.fillWithContent 上设置断点,并在调用函数之前检查 partnerPhoto 和/或 profilePhoto 是否为 nil。

关于swift - 具有真实数据的 UIImage init 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com