How to load UIImage from url?

2019-09-20 19:47发布

I have the following problem:

fatal error: unexpectedly found nil while unwrapping an Optional value

@IBOutlet weak var DetailImageView1: UIImageView!
@IBOutlet weak var DetailLabel: UILabel!

@IBOutlet weak var DetailLabel2: UILabel!

var SentData1: String!
var SentData2: String!
var SentData3: NSURL!

 override func viewDidLoad() {
    super.viewDidLoad()



    DetailLabel.text = SentData1
    DetailLabel2.text = SentData2
    let url = NSURL(string: "\(SentData3)")
    let data = NSData(contentsOfURL: url!)
    DetailImageView1.image = UIImage(data: data!)

I am taking the picture from a url and segue the url link from my previous view controller to this one. Then I created SentData3: NSURL! Now I have to show the picture in the DetailImageView1.image, but when I try to test the app I get an error.

I would be glad if someone can show me the mistake.

2条回答
虎瘦雄心在
2楼-- · 2019-09-20 19:55

If SentData3 is already a URL, you can just simply insert it. Don't force unwrap a variable when you are not sure whether it will return nil or not.

if let imageData: NSData = NSData(contentsOfURL: SentData3) {
    DetailImageView1.image = UIImage(data: imageData)
}
查看更多
小情绪 Triste *
3楼-- · 2019-09-20 20:14

This works for me...

var image: UIImage?
let urlString = "https://example.com/filename"

let url = NSURL(string: urlString)! as URL
if let imageData: NSData = NSData(contentsOf: url) {
    image = UIImage(data: imageData as Data)
}

..."image", will either be nil if there was an error, or it will contain the new UIImage object.

查看更多
登录 后发表回答