如何使用 URL 显示图像? [英] How to display an image using URL?

查看:25
本文介绍了如何使用 URL 显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The error is: "fatal error: unexpectedly found nil while unwrapping an Optional value"

我在 ViewController 中执行以下操作:

I am doing the following in ViewController:

var imageURL:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!)
    if data!= nil {
        imageURL.image = UIImage(data:data!)
    }
}

真不明白为什么会报错

imageURL.image = UIImage(data:data!)

虽然我已经告诉它如果数据为零则不要继续.不是链接的问题.数据"也不存在问题.我试图打印它,但它不是零.

while I already told it not to proceed if data is nil. It is not the problem of the link. Nor is there problem with the "data". I tried to print it and it was not nil.

推荐答案

该错误很可能是 imageURL 为零.你是在代码的其他地方给它赋值,还是在真正的代码中实际上是@IBOutlet?如果你不给它赋值,它将是 nil - 但它的 UIImageView! 类型意味着它是一个隐式解包的可选",这意味着编译器不会阻止你使用它,即使它是零,但会在运行时崩溃并出现您收到的错误.

The error is most likely that imageURL is nil. Are you assigning it a value elsewhere in the code, or is it actually @IBOutlet in the real code? If you do not assign a value to it, it will be nil - but its type of UIImageView! means it is an "implicitly unwrapped optional" which means the compiler won't stop you using it even if it is nil, but will crash at runtime with the error you're getting.

其余代码是正确的(假设 != 之前缺少的空格是编译代码中没有的拼写错误),但最好使用 if let 解开你的可选项,而不是根据 nil 来检查它们,然后使用 force-unwrap 操作符:

The rest of the code is correct (assuming the missing space before != is a typo not in your compiling code), but you would be better off using if let to unwrap your optionals rather than checking them against nil and then using the force-unwrap operator:

if let url = NSURL(string: "http://etc...") {
    if let data = NSData(contentsOfURL: url) {
        imageURL.image = UIImage(data: data)
    }        
}

如果您碰巧使用的是 Swift 1.2 测试版,则可以将这两个 if 组合在一起:

If you happen to be using the Swift 1.2 beta, you can combine the two ifs together:

if let url  = NSURL(string: "http://etc..."),
       data = NSData(contentsOfURL: url)
{
        imageURL.image = UIImage(data: data)
}

或者,如果您愿意,也可以使用 flatMap:

Or, if you prefer, use flatMap:

imageURL.image =
    NSURL(string: "http://etc...")
    .flatMap { NSData(contentsOfURL: $0) }
    .flatMap { UIImage(data: $0) }

这篇关于如何使用 URL 显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆