简体   繁体   English

Swift-在为Image中的NSdata解开可选值时意外发现nil

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

I am bringing the image URL from the webserice. 我要从网络服务中获取图像URL。 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 这是我的图片网址: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. 可以通过简单的nil检查来避免这种情况。

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

Use URL as which you can download it... 使用URL作为下载地址...

Code Below 下面的代码

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

  if let data = NSData(contentsOfURL: url){

      if let imageUrl = UIImage(data: data) {

         //UIImage
     }

 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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