0

I tried to show an image but the following error occurs:

error : fatal error: unexpectedly found nil while unwrapping an Optional value

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!)
    }
}
kelin
  • 11,323
  • 6
  • 67
  • 104
Saleem Khan
  • 150
  • 1
  • 9
  • I'd say this is not a duplicate. The NSURL isn't what fails to force unwrap. Its the misuse of `NSData(contentsOfURL:url!)` which is unintuitive because its not obvious in the docs, what this method actually does. – Joe Daniels Dec 08 '16 at 16:41

1 Answers1

0

From apples docs:

Important

Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.

Maybe consider using Alamofire for this task?

Alamofire.request(.GET, "http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg").response { (request, response, data, error) in
    self.imageURL.image = UIImage(data: data, scale:1)
}
Community
  • 1
  • 1
Joe Daniels
  • 1,646
  • 1
  • 11
  • 9