快速显示来自 URL 的图像,展开错误

Posted

技术标签:

【中文标题】快速显示来自 URL 的图像,展开错误【英文标题】:Display image from URL in swift, unwrapping error 【发布时间】:2015-02-07 11:48:58 【问题描述】:

我正在尝试从 URL 向 imageView 显示图像。我在一个简单的项目中使用同步方法成功地完成了它。但是这个应用程序用于在线商店,所以我从 JSON 文件中获取了产品信息和图像 URL。我确定我已成功将所有数据存储在产品数组中。但我面临的问题是:

致命错误:在展开可选值时意外发现 nil

这是代码。

// UnWrapping imageURL
        let url:NSURL? = NSURL(string: actualCurrentProduct.imageURL)

        if let actualURL = url 

            let imageData = NSData(contentsOfURL: actualURL)

            if let actualImageData = imageData 

               self.productImageView.image = UIImage(data: actualImageData)
            
        

它在这个特定的代码中突出显示。

self.productImageView.image = UIImage(data: actualImageData)

有人知道为什么吗?真的很感激。

【问题讨论】:

对我来说工作正常..检查你的 URL 可能是导致这个问题的原因。 也许self.productImageViewnil @DharmeshKheni 我检查了网址,它可以工作。 @rintaro 它不应该是零。我已经在每一行使用断点检查了它。 【参考方案1】:

我设法使用此代码从 URL 成功显示图像。我从头开始这个项目,对于显示图像部分,这是我的代码。

let imageURL = NSURL(string: actualCurrentProduct.imageURL)
        if let actualImageURL = imageURL 

            let imageData = NSData(contentsOfURL: actualImageURL)
            if let actualImageData = imageData 

                let image = UIImage(data: actualImageData)
                if let actualImage = image 

                    self.productImage.image = actualImage

                
            
        

终于……

【讨论】:

以上是关于快速显示来自 URL 的图像,展开错误的主要内容,如果未能解决你的问题,请参考以下文章