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

标签 ios swift swift2 nsurl loadimage

我有 load_image 函数并且可以使用

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

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

 load_image(detailDesc2!)

给出这个错误

fatal error: unexpectedly found nil while unwrapping an Optional value

我的代码在这里

ViewController 表格 View 选择代码。这里将 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)
    }

细节 View Controller

   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()
}

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

textbig.text = detailDesc1
textim.text = detailDesc2

最佳答案

由于某些原因,您的变量 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您可以通过以下方式使用 like 语句:

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.

希望对你有帮助

关于ios - Swift 2 从 url 变量加载图像错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32907689/

相关文章:

ios - 检查 URL 在 Swift 4 中是否有效

ios - Swift CollectionView 获取第一个单元格

ios - 在 iOS 9.3/Xcode 7.3 中使用 StoreKit 常量时使用未解析的标识符

objective-c - 如何拉伸(stretch) ImageView (iphone dev。)?

ios - 配置文件 - 在哪个文件夹中以及在 Xcode 中的哪个位置

ios - 将 UIApplication.shared.isIdleTimerDisabled 设置为 false 时屏幕变暗

ios - 如何从 NSMutableArray 创建 MPMediaCollection?

ios - UITableView 循环遍历单元格(我不希望它这样做)

iOS:强制 tableView 单元格在点击时动画更改

ios - 在uicollectionview(单选)中设置对所选单元格的影响ios swift