ios - 下载图像时检查 Nil 后变量显示 Nil

标签 ios swift uitableview firebase firebase-storage

请耐心听我解释这一点,

我正在创建一个聊天室,用户可以在其中上传照片供其他人查看。当用户点击图标时,他们可以将照片上传到我的 Firebase 数据库(这已成功完成,我已经对此进行了测试)。照片的 URL 被传递到消息数据库中并加载到我创建的 TableView 中(由于打印语句和检查数据库,我知道照片 URL 在那里)。然而,当我从 URL 下载照片时,应用程序崩溃,说在解开我的可选 (imageData) 时发现 nil - 这位于 if 语句内,我只应该在检查 imageData 不为零后执行该语句。在 if 语句之前我还有一个 print 语句,它确认数据不为零。为什么打开数据后发现为零?先谢谢您的帮助。

let notificationCell = tableView.dequeueReusableCell(withIdentifier: "messageImageCell", for: indexPath) as! MessageCellForPhotos

        notificationCell.clipsToBounds = true
        let newPhotoURL = NSURL(string: messagesArray[indexPath.row].userSentImage)! as URL

        print("\(newPhotoURL) Hello World This Time")

        DispatchQueue.global().async {
            let imageData = try? Data(contentsOf: newPhotoURL) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
            DispatchQueue.main.async {

                print(imageData)

                if imageData != nil {
                    notificationCell.sentImageView.image = UIImage(data: imageData!)
                }

            }
        }

        return notificationCell

最佳答案

您正在尝试从未完全检索的数据转换图像,因此请使用下面的库,这将为您提供通过 url 异步检索的更好结果。

Kingfisher

关于ios - 下载图像时检查 Nil 后变量显示 Nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50234459/

相关文章:

ios - 如何测试 iOS "Rate My App"功能

ios - 在 swift iOS 中使用 uipickerview 的 uialertcontroller?

swift - 为什么允许我创建多个 Singleton 实例,即使它的构造函数是私有(private)的?

ios - 如何获取 iOS 共享扩展以从 Safari 而不是 URL 获取网页内容

ios - 我可以创建页面大于屏幕尺寸的 UIPageControl/UIScrollview 吗?

ios - 如何快速组织uitableview的动态数量作为滑动页面

Swift playground 和 LeetCode OJ

iphone - 如果第一次填充,如何限制 tableview 第二次填充单元格

ios - 在 viewDidLoad 上显示来自 UITableView 的复选标记行

objective-c - UITableViewCell 和消失的分隔符