Swift 2 从 url 变量加载图像错误

Swift 2 load image from url variable error

我有 load_image 功能并使用

load_image("http://blabla.com/bla.png")

但是当我像这样添加变量时

 load_image(detailDesc2!)

出现这个错误

fatal error: unexpectedly found nil while unwrapping an Optional value

我的代码在这里

ViewController table 查看所选代码。这里将 detailDesc1 和 detailDesc 2 发送到 DetailView Controller

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let subcatVC = self.storyboard?.instantiateViewControllerWithIdentifier("Detail") as! DetailViewController
        subcatVC.detailDesc1 = self.arrayCategory[indexPath.row][API_PARAM_CAT_ID] as! String
        subcatVC.detailDesc2 = self.arrayCategory[indexPath.row][API_PARAM_CAT_IMAGE] as! String
        _ = UINavigationController(rootViewController: subcatVC)
        self.navigationController?.pushViewController(subcatVC, animated: false)
    }

详情ViewController

   var detailDesc1:String?
    var detailDesc2:String?

    load_image(detailDesc2!)  // HERE GIVES ERROR

我的load_image函数

func load_image(urlString:String)
{
    let imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)

    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request){
        (data, response, error) -> Void in

        if (error == nil && data != nil)
        {
            func display_image()
            {
                self.imagetbig.image = UIImage(data: data!)
            }

            dispatch_async(dispatch_get_main_queue(), display_image)
        }

    }

    task.resume()
}

此外,当我添加此代码时,成功工作标签和文本视图显示。

textbig.text = detailDesc1
textim.text = detailDesc2

我预计 self.arrayCategory[indexPath.row][API_PARAM_CAT_IMAGE] returns 无

您可以在使用前检查变量:

if let imageUrl = detailDesc2 {
    load_image(imageUrl)
}

出于某种原因,您的变量 detailDesc2nil 并且您使用 ! 强制解包告诉编译器当变量被声明为可选时变量总是有一个值(它可能没有价值)。根据Apple:

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

您可以使用 optional binding 避免运行时错误,在使用变量之前按以下方式检查:

if let url = detailDesc2 {
    load_image(url)
}

正如@LeoDabus 现在在 Swift 2 中推荐的那样,您也可以使用 guard 语句,您可以通过以下方式使用它:

guard if let url = detailDesc2 else {
   return 
}

load_image(url)

根据Apple

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.

希望对你有所帮助。