大家好!这让我抓狂,因为我不明白发生了什么。
我有两个TableViewControllers有一些类似的逻辑。
我使用1个数据模型。
这个模型包含用户信息,每个实体总是有一张照片。
初始化它,我使用下面的代码:
var partnerPhoto: UIImage? = nil
if let imageData = partners[indexPath.item].userPhoto {
partnerPhoto = UIImage(data: imageData as! Data)
}
在调试中partners[indexPath.item].userPhoto
有真实的数据,甚至imageData
显示4213字节。
但是,应用程序崩溃并出现典型错误:
编辑:致命错误:在展开可选值
时意外发现nil
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
}
解决方案:事实上,我还没有找到这个问题的具体解决方案,我只是从模型到视图控制器移动了一些逻辑。在模型中,我确实从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和/或profilepphoto是否为nil。
试试这个:
var partnerPhoto: UIImage?
guard let imageData = partners[indexPath.item].userPhoto else {return}
guard let image = UIImage(data: imageData) else {return}
partnerPhoto = image
在我的情况下返回nil,因为我试图通过Alamofire从FirebaseStorage下载图像,然后保存到核心数据。进入核心数据保存正确,我的photoData不是nil,但UIImage(data: photoData as Data)
返回nil。我通过检索图像原生方法FirebaseStorage:
func retrieveUserPhotoFromStorage(imageUID: String?, completion: @escaping (Result<Data, DomainError>) -> Void) {
guard let imageID = imageUID else { return }
let storageRef = storage.reference(withPath: DatabaseHierarhyKeys.users.rawValue).child(imageID)
storageRef.getData(maxSize: Constant.maxSize) { data, error in
guard let error = error else {
if let data = data {
completion(.success(data))
return
}
completion(.failure(.domainError(value: "errorRetrieveImage data nil")))
return
}
completion(.failure(.domainError(value: "errorRetrieveImage (error.localizedDescription)")))
}
}
然后保存到Core Data并且UIImage(data: photoData as Data)
已经不是nil