【问题标题】:Getting Image from URL for UIView [Swift]从 URL 获取 UIView 的图像 [Swift]
【发布时间】:2015-10-26 22:35:25
【问题描述】:

好的,所以我已经制作了一些处理程序和类来从 URL 中获取数据,它们都返回正常,我已经检查了 URL 是否有效并且一切正常。

无论如何,我正在尝试对 UIViewController 类中存储的 URL 执行 NSData(contentsOfURL)。我已成功打印出名称、类型、描述等字符串变量,但在将 UIImage 显示到 ViewController 上的图像视图中时遇到了困难。

这是我的代码,它在视图加载时运行:

func configureView() {
        // Update the user interface for the detail item.
        if let card = detailCard {
            title = card.cardTitle

            //Assign Elements
            detailDescriptionLabel?.text = card.description
            typeLabel?.text = card.cardType
            cardTitleLabel?.text = card.cardTitle
            costLabel?.text = card.cardCost

            print(card.cardImageURL)

            if let url = NSURL(string: card.cardImageURL){
                let data = NSData(contentsOfURL: url)
                imageView.image = UIImage(data: data!)// <--- ERROR HERE: EXC_BAD_INSTRUCTION
            }

            //Print Log
            //print(card.logDescription)
        }
    }

就像上面的评论所说,我在imageView.image = UIImage(data: data!) 行收到错误:

线程 1:EXC_BAD_INSTRUCTION

这是cardImageURL的代码:

var cardImageURL: String {
    return String(format: "http://testyard.example.net/display/images/cards/main/%@", image)
}
//This is a computed variable when a "Card" class object is created.

它以字符串形式返回正确的 url:

http://testyard.example.net/display/images/cards/main/armor-of-testing.jpg

我在别处用过这段代码,效果很好,为什么会在这里报错?

提前致谢。

【问题讨论】:

  • 你需要显示你是如何声明 card.cardImageURL
  • 请显示print(card.cardImageURL)的结果
  • 请查看我的编辑,谢谢。

标签: swift uiviewcontroller uiimageview uiimage


【解决方案1】:

您确定正在下载的数据是图像吗?您可能应该使用这一行:

if let image = UIImage(data: data)`

这应该会停止错误,但您可能需要测试您的数据是否实际包含图像。

【讨论】:

  • 所以我将代码更改为if let url = NSURL(string: card.cardImageURL){ let data = NSData(contentsOfURL: url) if let image = UIImage(data: data!){ imageView.image = image } } 并进入“if let image”代码并仍然返回错误。有什么想法吗?
  • 出于兴趣,如果你使用 let cgImage = CGImageCreateWithJPEGDataProvider(CGDataProviderCreateWithURL(url), nil, false, CGColorRenderingIntent.RenderingIntentDefault) 然后添加这个而不是 if let image:dispatch_async(dispatch_get_main_queue()) {imageView.image = UIImage(CGImage: cgImage!)} - 这行得通吗?
  • 想通了。添加一个“?”在 imageView 成功之后。所以:imageView?.image = image
  • 图像现在真的显示了吗?我以为你只需要添加 ?如果 imageView 可以为零。
  • 是的,它完全有效。虽然我对为什么不是 100% 有信心:/ 可能是因为 URL 本身包含在 If 语句中?
猜你喜欢
  • 2020-09-16
  • 2016-05-18
  • 2015-01-29
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 2018-02-19
相关资源
最近更新 更多