Fatal Error: Unexpectedly found nil while unwrapping an Optional value NSURL

Fatal Error: Unexpectedly found nil while unwrapping an Optional value NSURL

我收到零错误。但我不明白发生了什么。我可以通过打印获得选定的照片名称。但我不能在 NSUrl 中使用。你能帮我吗?

我的代码:

    print(selectedPhoto)

    if selectedPhoto != nil
    {
        let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
        print("photo url: \(photoUrl)")
        dataPhoto = NSData(contentsOfURL:photoUrl!)
        yemekResim.image = UIImage(data: dataPhoto!)
    }

    else
    {
        print("Error")
    }

替换为:

let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")

有了这个:

let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto!)")

(注意selectedPhoto后面的“!”)

来自苹果关于 NSData(contentsOfURL) 的文档

Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

如果您的应用程序因此崩溃,它将被商店拒绝。

相反,您应该使用 NSURLSession。在我的示例中使用 Async 回调块。 强制解包选项 ! 也不是一个好主意,因为你会得到 运行 时间错误,而不是使用 if let 语法

请参阅下面的示例。

if let photo = selectedPhoto{
            let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(photo)")
            if let url = photoUrl{
                NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
                    if let d = data{
                        dispatch_async(dispatch_get_main_queue(), {
                            if let image = UIImage(data: d) {
                                self.yemekResim.image = image
                            }
                        })


                    }
                }).resume()
            }
        }
    }