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

查看:115
本文介绍了如何使用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!)
    }
}

我真的不明白为什么会报告错误

I really don't understand why it will report an error on

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!意味着它是一个隐式解包的可选,这意味着编译器不会即使它是nil也停止使用它,但是在运行时会因为你得到的错误而崩溃。

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.

其余代码是正确的(假设缺少空间)在之前!= 是编译代码中不存在的错字),但如果让解包,最好使用您的选项而不是针对 nil 检查它们,然后使用强制解包运算符:

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 beta,你可以将两个ifs组合在一起:

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天全站免登陆