应用程序保持崩溃发现Nil Swift

时间:2014-11-14 21:22:10

标签: ios swift

我正在尝试在我的应用中显示网页视图。 webview的url是对象格式,因为我是从json获取的。所以在我的代码中,我将对象转换为NSString并尝试加载视图,但我的应用程序崩溃说:致命错误:在展开Optional值时意外发现nil。有没有更好的方法将对象转换为字符串?如何让webview显示网址内容?

制作详细项目:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let object: AnyObject = objectsPath[indexPath.row]
        (segue.destinationViewController as DetailViewController).detailItem = object
        }
    }
}

这是我的代码:

  var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() -> NSURLRequest {
        // Update the user interface for the detail item.
        let detail: AnyObject = self.detailItem!
        let stringURL: String = String(detail as NSString)
        let url = NSURL(string: stringURL)
        let request = NSURLRequest(URL: url!) <---ERROR occurs here
        return request



           // let string:St= detailItem!
          //  previewWebView.
           // println(string)
            //let url = NSURL(string: string)
            //let request = NSURLRequest(URL: url!)
            //self.previewWebView.loadRequest(request)

        }



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.previewWebView.loadRequest(configureView())

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1 个答案:

答案 0 :(得分:0)

您在configureView()内呼叫viewDidLoad()而不考虑self. detailItem的值。您应该在viewDidLoad()中调用此函数之前检查值,或者您应该修改configureView()以声明肯定值为self.detailItem