Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

ios - How to display an image using URL?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)
    }        
}

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)
}

Or, if you prefer, use flatMap:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...