简体   繁体   中英

Swift - unexpectedly found nil while unwrapping an Optional value for NSdata in Image

I am bringing the image URL from the webserice. and i am converting it to the Image from the below code.

I am getting error while unwrapping..

Below is my code

   let url = NSURL(string: contactResult.conImageUrl)
    let data = NSData(contentsOfURL: url!)
    var imageUrl: UIImage = UIImage()
    println("URL \(url)")
    println("data \(data)")
    imageUrl = UIImage(data: data!)! // here i am getting the error (unexpectedly found nil while      unwrapping an Optional value)

here my image URL: http://<...>/peoplefinder/imgs_styles/silhouette.jpg

Can someone please help me out as soon as possible?

You can safely unwrap your image as follow:

if let image = UIImage(data: data) {
    image  // you can use your image UIImage (note: image it is not an optional here)
}

It can be avoided by a simple nil check.

if data != nil
{
    imageUrl = UIImage(data: data!)!
}

Use URL as which you can download it...

Code Below

if let url = NSURL(string: "URL") {

  if let data = NSData(contentsOfURL: url){

      if let imageUrl = UIImage(data: data) {

         //UIImage
     }

 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM