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条回答
Fickle 薄情
2楼-- · 2019-01-08 12:07

Methode

extension UIImage {

/// Loads image asynchronously
///
/// - Parameters:
///   - url: URL of the image to load
///   - callback: What to do with the image

class func loadFromURL(url: NSURL, callback: (UIImage)->()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {

        let imageData = NSData(contentsOfURL: url)
        if let data = imageData {
            dispatch_async(dispatch_get_main_queue(), {
                if let image = UIImage(data: data) {
                    callback(image)
                }
            })
        }
    })
}

}

Usage

    let logoUrl = ImageService().buildImageString((self.uiConfig?.headerImage)!, imageMode: .Uniform, size: self.headerImage.frame.size)
    UIImage.loadFromURL(logoUrl, callback: { (image: UIImage) -> () in
        self.headerImage.image = image
    }) 
查看更多
Animai°情兽
3楼-- · 2019-01-08 12:10
NSURL(string: "") 

This returns an optional value. Take a look at description of it. It says An NSURL object initialized with URLString. If the URL string was malformed, returns nil.

In your code you are trying to url! which will get crash whenever the value of url is nil.

查看更多
可以哭但决不认输i
4楼-- · 2019-01-08 12:16

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) }
查看更多
做自己的国王
5楼-- · 2019-01-08 12:16
 let urlImg = NSURL(string:"https://firebasestorage.googleapis.com/v0/b/fanism-dccfe.appspot.com/o/Heros%2FIMG-20171116-WA0003.png?alt=media&token=b31a6d9e-cea6-422a-b198-82365abd845e")

    data = NSData.init(contentsOf: urlImg! as URL)
    if data != nil {
        imageView?.image = UIImage(data:data! as Data) //**Here imageView our ImageView outlet  **//
    }                                                                        
查看更多
时光不老,我们不散
6楼-- · 2019-01-08 12:17

You can set image in image view by using UIImageView+AFNetworking

Frist you drag the UIImageView+AFNetworking objective c classes in your project and import UIImageView+AFNetworking.h class in your project's bridge header file. And use this line to set image with placeholder in imageview. by this you can set multiple image in a view without any stuck.

yourImageview.setImageWithURL(NSURL(string: self.yourArray.objectAtIndex(indexPath.row).objectForKey("imageurl") as! String), placeholderImage: UIImage(named:"NoUserimage.png"))
查看更多
冷血范
7楼-- · 2019-01-08 12:18

Here is my code might help you

Swift 2:

extension UIImageView{

    func setImageFromURl(stringImageUrl url: String){

        if let url = NSURL(string: url) {
            if let data = NSData(contentsOfURL: url) {
                self.image = UIImage(data: data)
            }        
        }
    }
}

Swift 3:

extension UIImageView{

func setImageFromURl(stringImageUrl url: String){

      if let url = NSURL(string: url) {
         if let data = NSData(contentsOf: url as URL) {
            self.image = UIImage(data: data as Data)
         }
      }
   }
}

Usage

 let imgURL = "https://yourdomain.com/picturepath/picname.png" // or jpg
 self.myImage.setImageFromURl(stringImageUrl: imgURL)

if you are using HTTP connection and not https don't forget to add this

App Transport Security Settings as dictionary and into it Allow Arbitrary Loads as Boolean with value YES like in the below figure enter image description here

查看更多
登录 后发表回答