ios - fatal error : Unexpectedly found nil while unwrapping an Optional value NSURL

标签 ios swift null uiimage 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")
    }

最佳答案

来自苹果关于 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 回调 block 。 此外,强制解包选项 ! 也不是一个好主意,因为你会得到运行时错误,而不是使用 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()
            }
        }
    }

关于ios - fatal error : Unexpectedly found nil while unwrapping an Optional value NSURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37269618/

相关文章:

swift - 如何获取 Swift 4 中的类属性列表?

c# - 捕获的异常本身为空!

ios - 滚动 UIScrollView - 阻塞主线程

ios - removeGestureRecognizer 方法

iphone - 在iPhone上访问用户的短信

javascript - 在 HTML 源代码中查找所有空链接(包含 href ="x"的空标签)的最通用方法是什么?

c - 在函数中使用后将 char 指针设置为 NULL

ios - Xcode> Assets 1x 2x 3x 全屏图像

ios - UIDocumentInteractionController 显示空白 pdf

swift - UIScrollView contentOffset 在 Swift 中总是返回零