ios - Swift 2.0 fatal error : unexpectedly found nil while unwrapping an Optional value (lldb)

标签 ios swift fatal-error nsurl optional-values

let imgURL:NSURL = NSURL(string: "\(ImageName)")!

在上面一行,我遇到了 fatal error

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

代码:

let ImageName = obj["image"] as! String

 let imgURL:NSURL = NSURL(string: "\(ImageName)")!
 let request: NSURLRequest = NSURLRequest(URL: imgURL)

  let session = NSURLSession.sharedSession()

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

   if (error == nil && data != nil)
    {
       func display_image()
       {
           pointAnnoation.DisplayImage = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue(), display_image)
     }

   }

   Imgtask.resume()

从上面的代码我试图将我的图像从数据库中存储在注释中

如果我打印“ImageName”,它会从数据库中正确返回名称,但无法保留图像

它导致运行时出错。

最佳答案

你说的

if i printed the 'ImageName' it returns the name from the database correctly

那么这一定意味着 ImageName 对 URL 无效

如果您查看 description NSURL(string:) 它说:

The URL string with which to initialize the NSURL object. This URL string must conform to URL format as described in RFC 2396, and must not be nil. This method parses URLString according to RFCs 1738 and 1808.

所以问题是……ImageName 看起来怎么样?你能从中创建一个 URL 吗?

除此之外,使用 ? 而不是 ! 总是一个好主意,正如@PhillipMills 所说

更新:我看到您现在已经发布了您的 URL 示例。如果我在 Playground 上这样做:

let url = NSURL(string: "goo.gl/pBmA0d")

我得到 nil 作为返回,所以看起来短 URL 和 NSURL 不是最好的 friend 。

更新 2:嗯,我猜我说得很快,如果你看上面的内容,你会发现我在 goo.gl 部分之前有一个空格,如果我将其更改为:

let url = NSURL(string: "goo.gl/pBmA0d")

它确实有效,我得到了一个 NSURL 对象。

但我在您的代码中偶然发现了另一件事。您在此处将 ImageName 声明为字符串:

让 ImageName = obj["image"] as!字符串

所以你不必稍后将它包装在 \()

let imgURL:NSURL = NSURL(string: "\(ImageName)")!

你可以简单地说:

让 imageURL = NSURL(string: ImageName)

然后...正如其他人所说,使用 ? 而不是 ! 总是一个好主意

所以你可以这样写:

if let imageName = obj["image"] as? String,
   let imageURL = NSURL(string: imageName) {
   //we're in business :-)
}

平安无事

关于ios - Swift 2.0 fatal error : unexpectedly found nil while unwrapping an Optional value (lldb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178418/

相关文章:

swift - 从 CLLocationManager (Google Maps API) 获取用户位置的问题

ios - 按下完成后停止 AV 播放器

PHP SoapClient 即使在捕获异常后也会在脚本完成时触发 fatal error ?

compiler-errors - 编程新手,无法让Visual Studio 2013打开包含文件

ios - JTAppleCalendar 代表不适用于 Swift

ios - 如果我的 iOS 设备获得 MFI 许可证,我是否可以将其与自定义蓝牙设备配对?

ios - 自定义 UIStoryboardSegue 和 UIViewController 转换之间的区别

ios - Xcode 6 GM、IB Challenge 和 Swift

swift - JSQMessageViewController : fatal error: Index out of range

ios - NSRange非连续字符串搜索