How to display an image using URL?

2019-01-08 11:38发布

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.

标签: ios swift url
15条回答
劳资没心,怎么记你
2楼-- · 2019-01-08 11:55

Your code is right, just use:

if data != nil {

}
查看更多
甜甜的少女心
3楼-- · 2019-01-08 11:59

You can use SDWebImage for display image from URL https://github.com/rs/SDWebImage

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
查看更多
Fickle 薄情
4楼-- · 2019-01-08 12:00

Try writing:

if data != nil {}

instead:

if data!= nil {}

Compiler is maybe confusing exclamation mark with operation to unwrap the optional value.

查看更多
祖国的老花朵
5楼-- · 2019-01-08 12:01

Swift 3.0 for downloading image and parsing json using the URLSession and URLRequest.

static func getRequest(_ urlString:String, completion:@escaping (Any?) -> ()) {
    guard let url = URL(string: urlString) else { return }
    let session = URLSession.shared
    let request = URLRequest(url: url)

    let task = session.dataTask(with: request, completionHandler: {
        (data, response, error) -> Void in

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                completion(json)
            } catch {
                print(error)
            }
        }
    })
    task.resume()
}

static func downloadImage(_ url: String, completion:@escaping(UIImage?)->()) {
    let aUrl = URL(string: url)
    DispatchQueue.global().async {
        do {
            let data = try? Data(contentsOf: aUrl!)
            completion(UIImage(data: data!))
        } catch {
            print("Unable to download image")
        }
    }
}
查看更多
放荡不羁爱自由
6楼-- · 2019-01-08 12:05

This is the code for it. I have used this you do not need to include classes or anything else. Just use this extension. This is very fast.

extension UIImageView {
    public func imageFromURL(urlString: String) {

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        activityIndicator.startAnimating()
        if self.image == nil{
            self.addSubview(activityIndicator)
        }

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                activityIndicator.removeFromSuperview()
                self.image = image
            })

        }).resume()
    }
}
查看更多
别忘想泡老子
7楼-- · 2019-01-08 12:07

Here I have an approach from which you will not get any kind of crash when downloading image. Now currently you are using the following code:

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

Now change the code with this one, If you are continue with this approach:

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

    // It is the best way to manage nil issue. 
    if data.length > 0 {
        imageURL.image = UIImage(data:data!)
    } else {
        // In this when data is nil or empty then we can assign a placeholder image 
        imageURL.image = UIImage(named: "placeholder.png")
    }
}

And I am sure that If you are used it your nil crash will be solved.

查看更多
登录 后发表回答